0

I have a Base64 encoded file and I am trying the following to decode it:

[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($data)) 

However it generates the following error:

Exception calling "FromBase64String" with "1" argument(s): "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding 
characters, or an illegal character among the padding characters.

Although it is Base64, completely. Any ideas?

*Please note that it is Base64, but not encoded by PowerShell.

4
  • Can you check that the file does not have a UTF BOM at the start? Commented Mar 20, 2014 at 22:21
  • It does not have the mentioned
    – PnP
    Commented Mar 20, 2014 at 22:24
  • 2
    Although it is Base64, completely - I'm afraid I believe PowerShell saying it isn't more than I believe you saying it is. How are you creating $data - does it have line ending \n characters in it maybe? Commented Mar 20, 2014 at 22:41
  • If you are initializing $data with a literal string for e.g. "TestString" then it should not be a problem but if you are getting its value by executing another poweshell command for e.g. $data = <SomePowerShellCommand> then you will have to be cautious. Try seeing the value of $data variable using Write-Verbose on powershell before u actually use it later in code. I was doing something similar: $data = Get-AzureStorageKey -StorageAccountName $storageAccountName Here the Get-AzureStorageKey command returns an array of primary and secondary key while I was thinking it would return me a string.
    – RBT
    Commented Jun 26, 2015 at 14:52

2 Answers 2

3

If you would like to decode a Base64 string to text this will do:

$EncodedText = 'SGVsbG8gV29ybGQh'
$DecodedText = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($EncodedText))
$DecodedText

If you need to decode a Base64 string to a binary file this will do:

$base64string = ''
$FileName = "file.png"
[IO.File]::WriteAllBytes($FileName, [Convert]::FromBase64String($base64string))
1
  • Works like a charm for base64 encoded ZIP files, thank you. Took some time to find this WriteAllBytes method here. Thumbs up man!
    – Honza P.
    Commented Mar 21, 2020 at 15:14
0

Some applications require the Base64 string to end with one or two equal signs as the padding character. For a quick test you can add one or two "=" characters at the end of your variable $data like this:

[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($data+"="))

and try decoding again.

See Decoding Base64 with padding

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.