Hex和Base64

编码

编码就是将一种数据格式,转换成另一种格式。

常见的例子:数学中的进制转换,其实就是一种编码。

编码的用途:可以解决中文乱码、非法字符等问题,将数据转为更易于阅读的数据,方便人类查看,也方便程序读取。

注意:编码不是加密,编码之后的数据很容易还原,用于加密的话,只防君子而不防小人。

常用的编码:hex(十六进制)、base64、unicode、url 编码等等。

1. 解决乱码问题

通过编码,可以将字节码,转化为方便查看的字符串。

比如:使用 MD5 对字符串做摘要:

class Test{
    public static void main(String[] args) throws Exception {
        System.out.println(new String(DigestUtils.md5("啊哈iuashuai")));
    }
}

// 控制台显示:

// �X�L����={�=b��

虽然提取了数据摘要,但是看不懂是什么,并不方便保存,如果使用16进制进行编码:

class Test{
    public static void main(String[] args) throws Exception {
        System.out.println(Hex.encodeToString(DigestUtils.md5("啊哈iuashuai")));
    }
}


// 控制台显示:

// ab58f24ccbcecaef3d7bb73d621ffba5

进行16进制编码之后的数据,十分方便保存,可以读出来,告诉别人,存在数据库中,也方便查看。

2. 字符转义

再比如:value=a&b=c,特殊的情况下,我们希望表达的意思 value 等于字符串 "a&b=c",这时候就需要对 "a&b=c" 进行编码,使用的时候,再进行解码。

3. 数据存储

某些老旧的系统,前端上传文件时,会通过 base64 算法,将文件转换成字符串进行提交。

同理,这种方案,也可用于数据库存储。

16进制编码

代码选自 common-codec

public class Hex {
    public static String encodeToString(byte bytes[]) {
        char encodedChars[] = encode(bytes);
        return new String(encodedChars);
    }

    public static char[] encode(byte data[]) {
        int l = data.length;
        char out[] = new char[l << 1];
        int i = 0;
        int j = 0;
        for (; i < l; i++) {
            out[j++] = DIGITS[(240 & data[i]) >>> 4];
            out[j++] = DIGITS[15 & data[i]];
        }

        return out;
    }

    public static byte[] decode(String hex) {
        return decode(hex.toCharArray());
    }

    public static byte[] decode(char data[]) throws IllegalArgumentException {
        int len = data.length;
        if ((len & 1) != 0)
            throw new IllegalArgumentException("Odd number of characters.");
        byte out[] = new byte[len >> 1];
        int i = 0;
        for (int j = 0; j < len;) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f |= toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 255);
            i++;
        }

        return out;
    }

    protected static int toDigit(char ch, int index) throws IllegalArgumentException {
        int digit = Character.digit(ch, 16);
        if (digit == -1)
            throw new IllegalArgumentException((new StringBuilder()).append("Illegal hexadecimal charcter ").append(ch)
                    .append(" at index ").append(index).toString());
        else
            return digit;
    }

    private static final char DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f' };

}

Base64编码

代码选自阿里巴巴 druid.jar

public class Base64 {

    public Base64() {
    }

    public static String byteArrayToBase64(byte a[]) {
        return byteArrayToBase64(a, false);
    }

    public static String byteArrayToAltBase64(byte a[]) {
        return byteArrayToBase64(a, true);
    }

    private static String byteArrayToBase64(byte a[], boolean alternate) {
        int aLen = a.length;
        int numFullGroups = aLen / 3;
        int numBytesInPartialGroup = aLen - 3 * numFullGroups;
        int resultLen = 4 * ((aLen + 2) / 3);
        StringBuilder result = new StringBuilder(resultLen);
        char intToAlpha[] = alternate ? intToAltBase64 : intToBase64;
        int inCursor = 0;
        for (int i = 0; i < numFullGroups; i++) {
            int byte0 = a[inCursor++] & 255;
            int byte1 = a[inCursor++] & 255;
            int byte2 = a[inCursor++] & 255;
            result.append(intToAlpha[byte0 >> 2]);
            result.append(intToAlpha[byte0 << 4 & 63 | byte1 >> 4]);
            result.append(intToAlpha[byte1 << 2 & 63 | byte2 >> 6]);
            result.append(intToAlpha[byte2 & 63]);
        }

        if (numBytesInPartialGroup != 0) {
            int byte0 = a[inCursor++] & 255;
            result.append(intToAlpha[byte0 >> 2]);
            if (numBytesInPartialGroup == 1) {
                result.append(intToAlpha[byte0 << 4 & 63]);
                result.append("==");
            } else {
                int byte1 = a[inCursor++] & 255;
                result.append(intToAlpha[byte0 << 4 & 63 | byte1 >> 4]);
                result.append(intToAlpha[byte1 << 2 & 63]);
                result.append('=');
            }
        }
        return result.toString();
    }

    public static byte[] base64ToByteArray(String s) {
        return base64ToByteArray(s, false);
    }

    public static byte[] altBase64ToByteArray(String s) {
        return base64ToByteArray(s, true);
    }

    private static byte[] base64ToByteArray(String s, boolean alternate) {
        byte alphaToInt[] = alternate ? altBase64ToInt : base64ToInt;
        int sLen = s.length();
        int numGroups = sLen / 4;
        if (4 * numGroups != sLen)
            throw new IllegalArgumentException("String length must be a multiple of four.");
        int missingBytesInLastGroup = 0;
        int numFullGroups = numGroups;
        if (sLen != 0) {
            if (s.charAt(sLen - 1) == '=') {
                missingBytesInLastGroup++;
                numFullGroups--;
            }
            if (s.charAt(sLen - 2) == '=')
                missingBytesInLastGroup++;
        }
        byte result[] = new byte[3 * numGroups - missingBytesInLastGroup];
        int inCursor = 0;
        int outCursor = 0;
        for (int i = 0; i < numFullGroups; i++) {
            int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt);
            result[outCursor++] = (byte) (ch0 << 2 | ch1 >> 4);
            result[outCursor++] = (byte) (ch1 << 4 | ch2 >> 2);
            result[outCursor++] = (byte) (ch2 << 6 | ch3);
        }

        if (missingBytesInLastGroup != 0) {
            int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt);
            int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt);
            result[outCursor++] = (byte) (ch0 << 2 | ch1 >> 4);
            if (missingBytesInLastGroup == 1) {
                int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt);
                result[outCursor++] = (byte) (ch1 << 4 | ch2 >> 2);
            }
        }
        return result;
    }

    private static int base64toInt(char c, byte alphaToInt[]) {
        int result = alphaToInt[c];
        if (result < 0)
            throw new IllegalArgumentException((new StringBuilder()).append("Illegal character ").append(c).toString());
        else
            return result;
    }

    private static final char intToBase64[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/' };
    private static final char intToAltBase64[] = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':',
            ';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
            '3', '4', '5', '6', '7', '8', '9', '+', '?' };
    private static final byte base64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1,
            -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
            9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
            30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 };
    private static final byte altBase64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10,
            11, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28,
            29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 22, 23, 24,
            25 };

}

posted on 2018-05-23 21:46  疯狂的妞妞  阅读(11179)  评论(0编辑  收藏  举报

导航