为什么 base64/openssl 使用 'K' 的填充字符而不是 '='

Why do base64/openssl use a padding character of 'K' instead of '='

我注意到 php base64_encode 使用“=”作为填充字符。根据 Wikipedia,不同的类型使用“=”或 none。然而,CLI base64 命令以及 openssl enc -base64 使用 'K' 作为填充。我正在寻找有关他们使用的原因和实现方式的信息。

echo base64_encode('hello'); // aGVsbG8=
echo hello | base64 -i - // aGVsbG8K
openssl enc -base64 <<< hello   // aGVsbG8K

K 不是填充字符 。这是由 shell 命令添加的换行符的结果。

echo hello | openssl enc -base64 # aGVsbG8K
echo -n hello | openssl enc -base64 # aGVsbG8=

更新:

技术说明

Base64 将提供的 比特流转换为 6 位块 而不是 8 位块。然后 special table (other than the ascii table) 和 64 个仅可打印字符 (因此是编码名称)用于 convert 这些 6 位块到字符:

让我们在实践中看到它。 (print-bitsprint-b64-bits是虚构的命令)

换行:

echo hello | print-bits

# 01101000 (h) 01100101 (e) 01101100 (l) 01101100 (l) 01101111 (o) 00001010 (\n)

echo hello | print-b64-bits

# 011010 (a) 000110 (G) 010101 (V) 101100 (s) 011011 (b) 000110 (G) 111100 (8) 001010 (K)


没有换行符:

echo -n hello | print-bits

# 01101000 (h) 01100101 (e) 01101100 (l) 01101100 (l) 01101111 (o)

echo -n hello | print-b64-bits

# 011010 (a) 000110 (G) 010101 (V) 101100 (s) 011011 (b) 000110 (G) 111100 (8)

在后一种情况下,输出字符为 7。需要附加 = 字符以使它们成为 8(4 的乘积).

Note: A newline at the end is not always converted to K. It could be o or g. This depends on the number of input bytes. Consider the case below:

echo helllo | print-bits

# 01101000 (h) 01100101 (e) 01101100 (l) 01101100 (l) 01101100 (l) 01101111 (o) 00001010 (\n)

echo helllo | print-b64-bits

# 011010 (a) 000110 (G) 010101 (V) 101100 (s) 011011 (b) 000110 (G) 110001 (x) 101111 (v) 000010 (C) 10 (g)

在上述情况下,最后 2 位 将首先用零填充,然后转换为可打印字符。 最后一个输出字符现在是 g.

并且由于输出字符是 10,所以需要添加两个 = 使它们成为 12(4 的乘积)。