39

I use powershell to convert string

$Text = 'ouser:v3$34@#85b&g%fD79a3nf'
$Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText 

However when using https://www.base64decode.org/, or some java libraries for base64 encoding I get a different, shorter version.

Sample string:

This is a secret and should be hiden

powershell result:

VABoAGkAcwAgAGkAcwAgAGEAIABzAGUAYwByAGUAdAAgAGEAbgBkACAAcwBoAG8AdQBsAGQAIABiAGUAIABoAGkAZABlAG4A

normal base64 result:

VGhpcyBpcyBhIHNlY3JldCBhbmQgc2hvdWxkIGJlIGhpZGVu

While using the website I am able to decode both versions, however using my java code I am only able to decode the latter. Why is that? Is there more than one version of base64? Where those differences come from?

3
  • 10
    You're using Unicode encoding, meaning each character has two bytes, one is zero for ASCII. Use UTF8 instead.
    – woxxom
    Commented Aug 11, 2017 at 7:32
  • 32
    [System.Text.Encoding]::Unicode is UTF-16, the latter is UTF-8. There's [System.Text.Encoding]::UTF8 that you can use. Commented Aug 11, 2017 at 7:46
  • Indeed, the encoding was causing this behavior. Unfortunately you cannot mark comments as answers.
    – Zerg
    Commented Aug 11, 2017 at 8:19

1 Answer 1

40

Adding the comment from @Raziel as an answer for better discoverability of this question.

[System.Text.Encoding]::Unicode] is UTF-16, the later is UTF-8. There's [System.Text.Encoding]::UTF8 that you can use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.