I. Introduction to the Concept
Base64 is a representation of binary data based on 64 printable characters. Because of 2^6=64, every 6 bits is a unit, corresponding to a printable character. 3 bytes have 24 bits, corresponding to 4 Base64 units, 3 bytes can be represented by 4 printable characters. It can be used as the transmission encoding for e-mail. The printable characters in Base64 include the letter A-Z, A-Z, the number 0-9, which is 62 characters in total, and two printable symbols that differ from one system to another.
Base64 is often used to represent, transmit, and store some binary data in situations where text data is normally processed.
Two. Code calls
The code base provided in Golang can be called directly to implement BASE64 encoding and decoding, which provides encoding (and decoding) of data in both formats
const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"const encodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
From Golang source Base64.go
1. Standard data (ENCODESTD)
msg := "Mac" //编码 base64EncodedString := base64.StdEncoding.EncodeToString([]byte(msg)) fmt.Println("Base64编码后:", base64EncodedString) //解码 base64DecodedByte, err := base64.StdEncoding.DecodeString(base64EncodedString) if err != nil { log.Panic(err) } fmt.Println("Base64解码后的字节数组:", base64DecodedByte) fmt.Println("Base64解码后:", string(base64DecodedByte))
Return to print results
Base64编码后: TWFjBase64解码后的字节数组: [77 97 99]Base64解码后: Mac
2.URL data (Encodeurl)
msgUrl :="http://www.google.com" base64UrlEncodedString :=base64.URLEncoding.EncodeToString([]byte(msgUrl)) fmt.Println("Base64编码后:", base64UrlEncodedString) base64UrlDecodedByte,err := base64.URLEncoding.DecodeString(base64UrlEncodedString) if err !=nil { log.Panic(err) } fmt.Println("Base64解码后的字节数组:", base64UrlDecodedByte) fmt.Println("Base64解码后:", string(base64UrlDecodedByte))
Return to print results
Base64编码后: aHR0cDovL3d3dy5nb29nbGUuY29tBase64解码后的字节数组: [104 116 116 112 58 47 47 119 119 119 46 103 111 111 103 108 101 46 99 111 109]Base64解码后: http://www.google.com
Three. Coding principle
1. Convert each character to ASCII encoding (10 binary)
fmt.Println([]byte(msg)) //[77 97 99]
2. Turn the 10 binary code into a 2-in-binary encoding
Padded 8-bit:
3. Divide the 2 binary encoding by 6-bit group
010011 010110 000101 100011
4. Turn to 10 binary number
010011 ==> 1x2^0 + 1x2^1 + 0 + 0 + 1x2^4 = 19
010110 ==> 0 + 1x2^1 + 1x2^2 + 0 + 1x2^4 = 22
000101 ==> 1x2^0 + 0 + 1 x 2^2 + 0 + 0 + 0 = 5
100011 ==> 1x2^0 + 1x2^1 + 0 + 0 + 0 + 1x2^5 = 35
5. Use decimal numbers as indexes to find characters from BASE64 encoded tables
19 对应 T22 对应 W5 对应 F35 对应 j (注意是小写)
Attention
- If the text is 3 characters, it is exactly encoded as 4 characters long (3 8 = 4 6)
- If the text is 2 characters, it is encoded as 3 characters and the tail is padded with a "="
- If the text is 1 characters, it is encoded as 2 characters and the tail is padded with two "="