I. Encoding Rules:
Base64 encoding requires that three 8-bit bytes (3*8 = 24) be converted into four 6-bit bytes (4*6 = 24 ), then add two zeros before the six bits to form the 8-bit one-byte format.
For example, the string "3 ":
11010101 11000101 00110011
After conversion:
00110101 00011100 00010100 00110011
In decimal format: 53 34 20 51
This is not the final result. You also need to query the converted value based on the base64 encoding table. The following is the base64 encoding table:
Table 1: The base64 alphabet
Value encoding value Encoding
0 A 17 R 34 I 51 Z
1 B 18 S 35 J 52 0
2 C 19 t 36 K 53 1
3 D 20 u 37 L 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6g 23x40 o 57 5
7 H 24 y 41 P 58 6
8 I 25 Z 42 Q 59 7
9 J 26 A 43 R 60 8
10 K 27 B 44 s 61 9
11 l 28 C 45 t 62 +
12 m 29 D 46 U 63/
13 N 30 E 47 V (PAD) =
14 O 31 F 48 W
15 p 32G 49 x
16 Q 33 H 50 y
The preceding code is a total of 64 encodings, which is also the origin of the base64 name. The encoding number corresponds to the decimal value of the new byte. Therefore, in the preceding example, the string "3" is encoded as the string "1iuz.
WhenCodeIf the number is not an integer multiple of 3, the remainder of code/3 is 2 or 1. During conversion, if the result is less than six digits, 0 is used to fill in the corresponding position, and then two zeros are added before the six digits. After the empty output result is converted, "=" is used to fill the bits. For example, if the remaining result is two bytes of "sheets ":
String "Zhang"
11010101 HEX: D5 11000101 HEX: C5
00110101 00011100 00010100
Decimal 53 decimal 34 decimal 20 pad
'1' character 'I' character 'U' character '='
In this way, the last two bytes are sorted into "1iu = ".
Similarly, if the original code has only one byte left, two "=" will be added ". Only in these two cases, the base64 encoding can end with a maximum of two "="
Note: According to rfc822, a carriage return line is also required for every 76 characters.
Ii. encoding and decoding
It is very easy to implement base64 encoding and decoding in Java, because JDK already provides ready-made classes:
Encoding:
String src = "base64 encoding test ";
Sun. Misc. base64encoder en = new sun. Misc. base64encoder ();
String encodestr = en. encode (SRC. getbytes ());
Note: When the length of encodestr exceeds 76, there will be carriage return and line break
Decoding:
Sun. Misc. base64decoder dec = new sun. Misc. base64decoder ();
Byte [] DATA = dec. decodebuffer (decodestr );