我用mybatis对数据库进行访问,但是,在配置数据库连接的时候,用户名密码,是用的明文,所以,小编想对其进行加密。所以,我想到了Base64,也顺便研究一下咯。
先不说原理,我写了一小段程序,如下:
byte[] buffer = new byte[] { (byte) 0x01, (byte) 0x02, (byte) 0x03 };
// 对buffer进行Base64编码
buffer = Base64.getEncoder().encode(buffer);
// 输出结果
System.out.println(Arrays.toString(buffer));
for (int i = 0; i < buffer.length; i++) {
System.out.print((char) buffer[i] + " ");
}
#output:
[65, 81, 73, 68]
A Q I D
原理部分,转载 http://www.cnblogs.com/luguo3000/p/3940197.html 原文写得已经很详细了。
根据代码,自己再梳理一遍,加深印象:
1.首先3个字节转成4个字节;
2.由于新的自己只有6位,高位用0填充;
3.根据Base64的对照表,查到表对应的字符,对照表见下面;
4.获取字符,与程序输出的(#output)一致。
对照表:
好了decode的过程,就是encode的逆过程。
再有,我看到java.util.Base64的源码,确实也是通过查表来进行的:
/**
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648).
*/
private static final char[] toBase64 = {
'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', '+', '/'
};
收工