调用时 24 个字符的字符串有什么特别之处 base64.StdEncoding.DecodeString
What is so special about 24 characters string while calling base64.StdEncoding.DecodeString
24 个字符长的字符串有什么特别之处?
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []string{"24CharacterStringppppppp", "aaaaaaaaaaaaaaaaaaaaaaaa", "25CharacterStringpppppppp", "23CharacterStringpppppp", "qwertyuiop"}
for _, d := range data {
_, err := base64.StdEncoding.DecodeString(d)
if err != nil {
fmt.Printf("Failed to decode base 64 string %v, err: %v \n", d, err.Error())
} else {
fmt.Printf("No Error\n")
}
}
}
我只是偶然发现了这一点,任何长度为 24 个字符的字符串在调用 base64.StdEncoding.DecodeString
任何其他长度的字符串时都不会生成错误。
我错过了什么?
Because Base64 is a six-bit encoding, and because the decoded values are divided into 8-bit octets on a modern computer, every four characters of Base64-encoded text (4 sextets = 46 = 24 bits) represents three octets of unencoded text or data (3 octets = 38 = 24 bits). This means that when the length of the unencoded input is not a multiple of three, the encoded output must have padding added so that its length is a multiple of four.
24 是 4 的倍数,但 23 或 25 不是。但是如果你再添加 4 个字符,28 又是 4 的倍数,这也不会产生错误。
因此,例如这些输入都会生成 "No Error"
(在 Go Playground 上尝试):
data := []string{"", "1234", "12345678", "123456789012"}
24 个字符长的字符串有什么特别之处?
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []string{"24CharacterStringppppppp", "aaaaaaaaaaaaaaaaaaaaaaaa", "25CharacterStringpppppppp", "23CharacterStringpppppp", "qwertyuiop"}
for _, d := range data {
_, err := base64.StdEncoding.DecodeString(d)
if err != nil {
fmt.Printf("Failed to decode base 64 string %v, err: %v \n", d, err.Error())
} else {
fmt.Printf("No Error\n")
}
}
}
我只是偶然发现了这一点,任何长度为 24 个字符的字符串在调用 base64.StdEncoding.DecodeString
任何其他长度的字符串时都不会生成错误。
我错过了什么?
Because Base64 is a six-bit encoding, and because the decoded values are divided into 8-bit octets on a modern computer, every four characters of Base64-encoded text (4 sextets = 46 = 24 bits) represents three octets of unencoded text or data (3 octets = 38 = 24 bits). This means that when the length of the unencoded input is not a multiple of three, the encoded output must have padding added so that its length is a multiple of four.
24 是 4 的倍数,但 23 或 25 不是。但是如果你再添加 4 个字符,28 又是 4 的倍数,这也不会产生错误。
因此,例如这些输入都会生成 "No Error"
(在 Go Playground 上尝试):
data := []string{"", "1234", "12345678", "123456789012"}