I. base64 encoding rules
Base64 encoding uses 64 basic ASCII characters to re-encode the data. It splits the data to be encoded into byte arrays. Take 3 bytes as a group. Sort the 24-bit data in order and divide the 24-bit data into four groups, that is, 6-bit data in each group. Add two zeros before the highest bits in each group to make up one byte. In this way, a 3-byte data is reencoded into 4 bytes. When the number of bytes of the data to be encoded is not an integer multiple of 3, that is to say, the last group is not three bytes long. At this time, fill in 1 to 2 0 bytes in the last group. Add 1 to 2 "=" at the end after the final encoding ".
For example, base64 encoding will be performed on ABC:
1. Obtain the ASCII code value corresponding to ABC. A (65) B (66) C (67);
2. Obtain the binary value A (01000001) B (01000010) C (01000011 );
3. Connect the three bytes of binary code (010000010100001001000011).
4. Divide the three bytes into four data blocks in 6 bits, and fill in two zeros at the highest bit to form a 4-byte encoded value (00 010000 ) (00 010100 ) (00 001001 ) (00 000011 ), the blue part indicates the actual data.
5. Convert the four bytes into hexadecimal values (16) (20) (9) (3 );
6. Check the corresponding ASCII code (q) (u) (j) (d) Based on the 64 basic sequence tables provided by base64 ), the value here is actually the index of the data in the orders table.
Note: base64 sequence table: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 +/
Ii. decoding rules
The decoding process is to restore 4 bytes to 3 bytes, and then reorganize the byte array into data according to different data forms.
Iii. Implementation in C #
Code
// Base 64 encode
Byte [] Bytes = Encoding. Default. getbytes ( " Helloworld " );
String Str = Convert. tobase64string (bytes );
Console. writeline (STR );
Console. Readline ();
// Base 64 decode
Bytes = Convert. frombase64string (STR );
Console. writeline (encoding. Default. getstring (bytes ));
Console. Readline ();