bash 如何在 linux 上对字符串进行 base64 编码,使其与 Windows“Unicode.GetBytes.ToBase64String”匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37996640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:49:00  来源:igfitidea点击:

How can I base64 encode a string on linux so it matches windows "Unicode.GetBytes.ToBase64String"?

linuxbashpowershellcharacter-encodingbase64

提问by user331465

This question probably has been answered, but I couldn't find it

这个问题可能已经回答了,但我找不到

Question

How can I 'base64 encode' a string in bash so it matches "what windows expects", i.e. "Unicode.GetBytes.ToBase64String"

如何在 bash 中对字符串进行“base64 编码”,使其匹配“windows 期望的内容”,即“Unicode.GetBytes.ToBase64String”

Context

语境

The powershell help text has this example

powershell 帮助文本有这个例子

$command='dir'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
echo $encodedCommand
powershell.exe -encodedCommand $encodedCommand

Windows Output

窗口输出

The encoded output is this:

编码后的输出是这样的:

ZABpAHIA

Very Different results on linux

在 linux 上的结果非常不同

If I do the same thing on linux, I get this:

如果我在 linux 上做同样的事情,我会得到这个:

echo "dir" | base64
ZGlyCg==

Encodings?

编码?

I've tried using "iconv" to convert encodings, but no luck, i.e same results.

我试过使用“iconv”来转换编码,但没有运气,即相同的结果。

echo dir |iconv -f ASCII -t UTF-8 |base64

echo dir |iconv -f ASCII -t UTF-8 |base64

Differences

差异

So you can see two differences:

所以你可以看到两个不同之处:

  • Alphanumeric characters differ
  • Trailing "===" appears on linux
  • 字母数字字符不同
  • 尾随“===”出现在 linux 上

回答by Frode F.

Unicode in Powershell is UTF16 LE, not UTF8.

Powershell 中的 Unicode 是 UTF16 LE,而不是 UTF8。

Unicode: Encodes in UTF-16 format using the little-endian byte order.

Unicode:使用 little-endian 字节顺序以 UTF-16 格式编码。

Source: Set-Content for FileSystem

来源:文件系统的设置内容

I don't use linux, but if your utf8-sample above works, then you could try:

我不使用 linux,但如果你上面的 utf8-sample 工作正常,那么你可以尝试:

iconv -f ASCII -t UTF-16 mycmd.txt |base64

If you plan to bring a string encoded in Powershell into Linux then do the following, first encode in Powershell

如果您打算将在 Powershell 中编码的字符串带入 Linux,请执行以下操作,首先在 Powershell 中编码

$string = "That's no moon!"
[system.convert]::ToBase64String([System.Text.Encoding]::unicode.getbytes($String))

VABoAGEAdAAnAHMAIABuAG8AIABtAG8AbwBuACEA

Then in Linux do the following:

然后在 Linux 中执行以下操作:

echo VABoAGEAdAAnAHMAIABuAG8AIABtAG8AbwBuACEA | base64 -d | iconv -f utf-16 -t utf-8; echo

That's no moon!