Base64 is one of the most common encoding methods used to transmit 8-bit code on the network. When sending an email, the user name and password for server authentication must be base64 encoded, the attachment must also be base64-encoded.
The following describes the principles of the base64 algorithm. Because the code is too long, it will not be posted here.
Base64 requires that each three 8-bit bytes be converted into four 6-bit bytes (3*8 = 4*6 = 24), and then 6-bit bytes be added with two more high 0 values, it consists of four 8-bit bytes. That is to say, the converted string is theoretically 1/3 longer than the original one.
After conversion, we use a code table to obtain the desired string (that is, the final base64 encoding). This table is like this:
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
14 O 31 F 48 W (PAD) =
15 p 32G 49 x
16 Q 33 H 50 y
0 is used to supplement the last three bytes in the original text, and the base64 encoding is replaced by =. This is why some base64 encoding ends with one or two equal signs, but the equal signs can only be two at most.
For example, after base64 encoding, ABC returns ywjj.
- Private Static final string charset_name = "iso8859_1 ";
- Public static byte [] base64decode (string s) throws ioexception,
- Javax. Mail. messagingexception {
- If (S = NULL | S. Length () = 0 ){
- Return NULL;
- }
- Bytearrayinputstream BAIS = new bytearrayinputstream (S
- . Getbytes (charset_name ));
- Inputstream is = mimeutility. Decode (BAIS, "base64 ");
- Bytearrayoutputstream out = new bytearrayoutputstream ();
- Int CH =-1;
- While (CH = is. Read ())! =-1 ){
- Out. Write (CH );
- }
- Out. Flush ();
- BAIS. Close ();
- Return out. tobytearray ();
- }
- Public static string base64encode (byte [] BUF) throws ioexception,
- Javax. Mail. messagingexception {
- If (BUF = NULL | Buf. Length = 0 ){
- Return "";
- }
- Inputstream is = new bytearrayinputstream (BUF );
- Bufferedinputstream Bis = new bufferedinputstream (is );
- Bytearrayoutputstream baos = new bytearrayoutputstream ();
- Outputstream OS = javax. Mail. Internet. mimeutility
- . Encode (baos, "base64 ");
- Int CHR =-1;
- While (CHR = bis. Read ())! =-1 ){
- OS. Write (CHR );
- }
- Bis. Close ();
- Baos. Close ();
- Return new string (baos. tobytearray (), charset_name );
- }