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

19,337

Unicode in Powershell is UTF16 LE, not UTF8.

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

Source: Set-Content for FileSystem

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

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

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

VABoAGEAdAAnAHMAIABuAG8AIABtAG8AbwBuACEA

Then in Linux do the following:

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

That's no moon!
Share:
19,337
user331465
Author by

user331465

Updated on June 28, 2022

Comments

  • user331465
    user331465 almost 2 years

    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"

    Context

    The powershell help text has this example

    $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

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

    echo "dir" | base64
    ZGlyCg==
    

    Encodings?

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

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

    Differences

    So you can see two differences:

    • Alphanumeric characters differ
    • Trailing "===" appears on linux