Skip to content

Improvements and bugfixes #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions BinaryToPowershellScript/BinaryToPowershellScript.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
$ActualCompress=$true
}
else {
Write-Host -NoNewline "compression is useless, disabling it..."
Write-Host -NoNewline "compressed file [$([Math]::Round($compressedFileBytes.Length/1024))KB] is longer than original file [$([Math]::Round($inputFileBytes.Length/1024))KB], disabling compression..."
$ActualCompress=$false
}
}
Expand Down Expand Up @@ -96,7 +96,12 @@

[void] $script.Append("`n`tcreateFile `'$file`' `$bytes `$password $hashParameter $decompressParameter`n`n")
if (!$SingleFile) {
[void] $script.Append("`}`n`ncreateFiles `'$Password`'`n")
if ([System.String]::IsNullOrEmpty($Password)) {
[void] $script.Append("`}`n`ncreateFiles `'`'`n")
}
else {
[void] $script.Append("`}`n`ncreateFiles ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host `'Enter password`' -AsSecureString))))`n")
}

$outputScript = $script.ToString()
[System.IO.File]::WriteAllText($outputFile,$outputScript)
Expand All @@ -109,7 +114,12 @@
}
if ($SingleFile)
{
[void] $script.Append("`}`n`ncreateFiles `'$Password`'`n")
if ([System.String]::IsNullOrEmpty($Password)) {
[void] $script.Append("`}`n`ncreateFiles `'`'`n")
}
else {
[void] $script.Append("`}`n`ncreateFiles ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host `'Enter password`' -AsSecureString))))`n")
}

$outputScript = $script.ToString()
[System.IO.File]::WriteAllText($outputFile,$outputScript)
Expand All @@ -135,7 +145,7 @@
}
else {
$InputMemoryStream.CopyTo($stream)
$stream.Flush()
$stream.Dispose()
}

$result = $OutputMemoryStream.ToArray()
Expand Down Expand Up @@ -252,7 +262,7 @@
`t}
`telse {
`t`t`$InputMemoryStream.CopyTo(`$stream)
`t`t`$stream.Flush()
`t`t`$stream.Dispose()
`t}

`t`$result = `$OutputMemoryStream.ToArray()
Expand Down
20 changes: 13 additions & 7 deletions BinaryToPowershellScript/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
else
{
inputMemoryStream.CopyTo(stream);
stream.Flush();
stream.Dispose();
}

return outputMemoryStream.ToArray();
Expand Down Expand Up @@ -138,7 +138,7 @@
}
else {
$InputMemoryStream.CopyTo($stream)
$stream.Flush()
$stream.Dispose()
}

$result = $OutputMemoryStream.ToArray()
Expand Down Expand Up @@ -235,7 +235,7 @@
}
}
";
var hashCode = o.Hash ? hashCodeMultiRow : String.Empty;
var hashCode = o.Hash ? hashCodeMultiRow : String.Empty;


script.Append($@"function createFile {{
Expand Down Expand Up @@ -278,7 +278,7 @@

var outputFile = Path.Combine(o.OutputFolder, $"SingleScript.ps1");

foreach (var input in o.Inputs)

Check warning on line 281 in BinaryToPowershellScript/Program.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 281 in BinaryToPowershellScript/Program.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
{
var actualCompress = false;

Expand All @@ -302,13 +302,13 @@
{
var compressedFileBytes = CopyBytesToStream(inputBytes, false, encryptedStream => new DeflateStream(encryptedStream, CompressionMode.Compress));

if (compressedFileBytes.Length>0 && compressedFileBytes.Length < inputBytes.Length)
if (compressedFileBytes.Length > 0 && compressedFileBytes.Length < inputBytes.Length)
{
inputBytes = compressedFileBytes;
actualCompress = true;
}
else
Console.Write("compression is useless, disabling it...");
Console.Write($"compressed file [{Math.Round(compressedFileBytes.Length * 1.0 / 1024)}KB] is longer than original file [{Math.Round(inputBytes.Length * 1.0 / 1024)}KB], disabling compression...");

}

Expand Down Expand Up @@ -340,7 +340,10 @@

if (!o.SingleFile)
{
script.Append($"}}\n\ncreateFiles '{o.Password}'\n");
if (String.IsNullOrEmpty(o.Password))
script.Append($"}}\n\ncreateFiles ''\n");
else
script.Append($"}}\n\ncreateFiles ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host 'Enter password' -AsSecureString))))\n");

var outputScript = script.ToString();
File.WriteAllText(outputFile, outputScript);
Expand All @@ -353,7 +356,10 @@

if (o.SingleFile)
{
script.Append($"}}\n\ncreateFiles '{o.Password}'\n");
if (String.IsNullOrEmpty(o.Password))
script.Append($"}}\n\ncreateFiles ''\n");
else
script.Append($"}}\n\ncreateFiles ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host 'Enter password' -AsSecureString))))\n");

var outputScript = script.ToString();
File.WriteAllText(outputFile, outputScript);
Expand Down
114 changes: 114 additions & 0 deletions BinaryToPowershellScript/SendFileOrKeys.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<#
.SYNOPSIS

Sends a string or a text file as keypresses on the keyobard

.DESCRIPTION

You must specift at least either Filename or Keys parameter.
You can also specify an optional Delay in seconds and a WindowTitle to activate before sending the keypresses.

.PARAMETER Filename
Specifies the file name, alternative to Keys parameter

.PARAMETER Keys
Specifies the keys, alternative to Filename parameter

.PARAMETER Delay
Specifies the amount of time in seconds to wait before starting sending the keypresses

.PARAMETER WindowTitle
Specifies the window title to activate before starting sending the keypresses

.INPUTS

None.

.OUTPUTS

None

.EXAMPLE

PS> SendFileOrKeys -f "BinaryToPowershellScript.ps1" -d 10

.EXAMPLE

PS> SendFileOrKeys -k "Write-Host 'Hello how are you ?'" -w "Powershell 7 (x64)"

.EXAMPLE

PS> SendFileOrKeys -k "Write-Host 'Hello how are you ?'"

.LINK

https://github.com/fededim/BinaryToPowershellScript

.NOTES

Implementation of this script is partially borrowed from https://superuser.com/questions/1249976/sendkeys-method-in-powershell.
Remember to set English keyboard, the SendKeys api does not support other keyboards!
#>
function SendFileOrKeys {
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)] [Alias('f')] [String] $Filename,
[Parameter(Mandatory=$false)] [Alias('k')] [String] $Keys,
[Parameter(Mandatory=$false)] [Alias('d')] [Nullable[int]] $InitialDelay=$null,
[Parameter(Mandatory=$false)] [Alias('i')] [int] $IntraChunkDelayMs=200,
[Parameter(Mandatory=$false)] [Alias('c')] [int] $ChunkSize=100,
[Parameter(Mandatory=$false)] [Alias('w')] [String] $WindowTitle=$null
)

[System.IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location).Path))

$wshell = New-Object -ComObject wscript.shell;

If (![System.String]::IsNullOrEmpty($WindowTitle)) {
$wshell.AppActivate($WindowTitle)
if ($InitialDelay -eq $null) {
$InitialDelay = 1
}
}

If ($InitialDelay -ne $null) {
Start-Sleep $InitialDelay
}

If (![System.String]::IsNullOrEmpty($Filename)) {

$text = (EncodeForSendKeys ([System.IO.File]::ReadAllText($Filename)))
Set-Content -Path ".\out.txt" -Value $text

$wshell.SendKeys($text)

#$keypresses = [System.Text.RegularExpressions.Regex]::Replace([System.IO.File]::ReadAllText($Filename),"[+^%~(){}]", "{`$0}")
#Set-Content -Path ".\out.txt" -Value $keypresses

#for ($i=0;$i -lt $keypresses.Length;$i+=$ChunkSize) {
# $wshell.SendKeys($keypresses.Substring($i, [System.Math]::Min($ChunkSize, $keypresses.Length-$i)))
# Start-Sleep -Milliseconds $IntraChunkDelayMs
#}

#$lines = [System.IO.File]::ReadAllLines($Filename)

#foreach ($line in $lines) {
# $wshell.SendKeys((EncodeForSendKeys $line))
# Start-Sleep -Milliseconds $IntraChunkDelayMs
#}
}
else {
$wshell.SendKeys((EncodeForSendKeys $Keys))
}
}


function EncodeForSendKeys {
[OutputType([String])]
param ([String] $string)

$encode = [System.Text.RegularExpressions.Regex]::Replace($string,"[+^%~(){}]", "{`$0}")
$adjustNewLines = [System.Text.RegularExpressions.Regex]::Replace($encode,"(`r`n|`r|`n)+", " %(096){ENTER}")

return $adjustNewLines.Replace("`t","{TAB}")
}