Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding base64 with powershell

I'm attempting to decode an attachment in an email file from base64 and save it to disk.

For testing purposes, this is my code. Where input.txt contains just the base64 encoded data, which is an HTML file.

$file = "C:\input.txt"
$data = Get-Content $file
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($data)) > out.html

The decoding works fine, and it generates a new file that contains all of the lines, and is visibly identical to the original attachment. The problem is that the output file is twice the size (actually (filesize*2)+6 bytes, in this case).

Am I decoding this improperly? I've also tried UTF8 instead of ASCII... same result.

like image 201
user2766136 Avatar asked Sep 10 '13 18:09

user2766136


People also ask

Can PowerShell decode Base64?

In this regard, we shared with you the PowerShell commands that help in performing the Base64 encoding and decoding of the desired data. By making use of these commands, you can easily encode and decode any given strings with the Base64 coding in PowerShell in Windows 10.

How do I decode Base64 encoded strings in Windows?

If you are using a Windows system, there is no built-in command to directly perform Base64 encoding and decoding. But you can use the built-in command "certutil -encode/-decode" to indirectly perform Base64 encoding and decoding.

What is Base64 encoded PowerShell?

PowerShell Base64 is a technique or mechanism that is used to encode and decode data. The encoding and decoding are important in order to prevent the data from malware attacks. Base64 encoding and decoding is a popular method to encrypt and decrypt the data.


2 Answers

Well I got it working. Who knew Out-File re-encoded to Unicode by default? Solved by doing the following:

$file = "C:\input.txt"
$data = Get-Content $file
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($data)) | Out-File -Encoding "ASCII" out.html
like image 108
user2766136 Avatar answered Oct 12 '22 02:10

user2766136


This one-liner preserves the original encoding of the base64 encoded file, so it will work with binary files such as a PDF or ZIP. Change ".\input.txt" and output.bin as needed - this will take .\input.txt, base 64 decode it, and then write the bytes out to output.bin exactly as they were when the file was encoded.

$file = ".\input.txt"; [System.Convert]::FromBase64String((Get-Content $file)) | Set-Content output.bin -Encoding Byte
like image 44
NYCdotNet Avatar answered Oct 12 '22 01:10

NYCdotNet