如何给PowerShell脚本加密


PowerShell交流中心如何给PowerShell脚本加密
0
liyuan asked 8 年 ago

哪位大神 能给一个小程序, 把powershell 的文件加密,但不会影响 这个文件使用

1 Answers
4
Best Answer
Mooser Lee 管理员 answered 8 年 ago

PowerShell本身是支持base64格式的:
我们可以通过下面的函数,将一个PowerShell脚本文件转换成bat批处理文件。支持双击运行:

function Encrypt-Script{
param(
[system.io.fileinfo]$File
)

if($File.Exists){
$fileContent = Get-Content $File -Raw
$bytes = [System.Text.Encoding]::Unicode.GetBytes($fileContent)
$encodedCommand = [Convert]::ToBase64String($bytes)
$batFile=$File.FullName+".bat"
"call $PSHOME\powershell.exe -encodedCommand `"$encodedCommand`""  | Out-File $batFile -Encoding ascii
Write-Host "加密的脚本已保存至 $batFile"
}
}
Encrypt-Script -File 'E:\ps\WorkingHours.ps1'

函数允许后会在脚本的同一目录生成一个E:\ps\WorkingHours.ps1.bat 双击运行即可。
bat文件的里面的内容大概类似这样:

call C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -encodedCommand "IwC/i+6VaAB0AHQAcAA6AC8ALwBoAHIAaQBuAHQALgBzAGgALgBjAHQAc*******AA=="

解密的脚本可参考:

function Decrypt-Script
{
param([system.io.fileinfo]$File)

$body = Invoke-Expression ((Get-Content $File.FullName -Raw ) -split ' ' | select -Last 1)
$byte = [Convert]::FromBase64CharArray($body,0,$body.Length)
$script = [System.Text.Encoding]::Unicode.GetString($byte)
$psFile = $File.FullName + ".ps1"
$script | Out-File $psFile
Write-Host "解密的脚本已经保存到 $psFile"
}

Decrypt-Script -File E:\ps\WorkingHours.ps1.bat
默默 无闻 replied 8 年 ago

不错奥

Qiqi replied 8 年 ago

这个可以编写程序解密这个bat批处理文件吗?

Mooser Lee 管理员 replied 8 年 ago

已在原答案上更新了。

Shengjie_Luo replied 4 年 ago

@Mooser Lee 请问该脚本加密是不是有长度限制?当我ps1中较多的demo时,它生成的bat文件不会生效。