Java之Base64

我用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', '+', '/'
        };

收工






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章