我无法找到使用非对称加密的良好PowerShell功能,因此我创建了以下内容.想要改进方面的任何反馈,因为我是一个加密菜鸟.需要注意的是,这些功能非常基础.没有错误检查,并且几乎不需要解密后的写主机.只是想在添加受保护的内存之类的东西之前建立核心功能.
这已经成功地测试了两个系统:Win8的W/Powershell的V3和Win2008R2 W/PowerShell的V2.
Function Encrypt-Asymmetric([string]$Encrypt,[string]$CertPath,[string]$XmlExportPath)
{
# Encrypts a string with a public key
$pubcer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertPath)
$byteval = [System.Text.Encoding]::UTF8.GetBytes($Encrypt)
$pubcer.PublicKey.Key.Encrypt($byteval,$true) | Export-Clixml -Path $XmlExportPath
}
Function Decrypt-Asymmetric([string]$XmlPath,[string]$CertThumbprint)
{
# Decrypts cipher text using the private key
# Assumes the certificate is in the LocalMachine store
$store = new-object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
$store.open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
$cer = $store.Certificates | %{if($_.thumbprint -eq $CertThumbprint){$_}}
$ciphertext = Import-Clixml -Path $XmlPath
$decryptedBytes = $cer.PrivateKey.Decrypt($ciphertext,$true)
$ClearText = [System.Text.Encoding]::UTF8.GetString($decryptedBytes)
Write-Host $ClearText
}
Run Code Online (Sandbox Code Playgroud)