Encode / Decode .EXE in Base64

I have a .NET exe file that I would like to encode into a Base-64 string, and then at a later point decode a .exe file from a Base64 string using Powershell.

That I still create the .exe file , however, this file is not recognized for windows as an application that can run, and is always different from the file, m, which go into the script encoding.

I think I can use the wrong encoding here, but I'm not sure.

Encode script:

Function Get-FileName($initialDirectory) { [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog.initialDirectory = $initialDirectory $OpenFileDialog.filter = "All files (*.*)| *.*" $OpenFileDialog.ShowDialog() | Out-Null $FileName = $OpenFileDialog.filename $FileName } #end function Get-FileName $FileName = Get-FileName $Data = get-content $FileName $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Data) $EncodedData = [Convert]::ToBase64String($Bytes) 

Decoding script:

 $Data = get-content $FileName $Bytes = [System.Text.Encoding]::UTF8.GetBytes($Data) $EncodedData = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Bytes)) $EncodedData | Out-File ( $FileName ) 
+6
source share
2 answers

The problem is caused by:

  • Get-Content without -raw splits the file into an array of strings, thereby destroying the code
  • Text.Encoding interprets the binary as text, thereby destroying the code
  • Out-File is for text data, not binary.

The correct approach is to use IO.File ReadAllBytes :

 $base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($FileName)) 

and WriteAllBytes for decoding:

 [IO.File]::WriteAllBytes($FileName, [Convert]::FromBase64String($base64string)) 
+14
source

Just add an alternative for people who want to do a similar task: Windows comes with certutil.exe (a certificate management tool) that can encode and decode base64 files.

 certutil -encode test.exe test.txt certutil -decode test.txt test.exe 
+7
source

Source: https://habr.com/ru/post/1015466/


All Articles