2013-06-07 4 views
1

Мне не удалось найти хорошие функции powershell для использования асимметричного шифрования, поэтому я создал следующее. Хотелось бы получить любую обратную связь с точки зрения улучшения, поскольку я криптоват. С оговоркой, что эти функции очень основные. Существует не проверка ошибок, и запись-хост после расшифровки вряд ли нужна. Просто хочу установить базовую функциональность, прежде чем добавлять такие вещи, как защищенная память и т. Д.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 
} 
+0

У вас есть конкретный вопрос? Просто просить общую обратную связь не подходит для этого сайта. – zdan

+0

@zdan. Поскольку я криптоват, я беспокоюсь, правильно ли я использую криптографические функции. Сопоставляя приведенные выше строки, я столкнулся с этим сообщением [http://stackoverflow.com/questions/7539984/asymetric-cryptography-example-in-c-sharp/7540173#7540173](http://stackoverflow.com/questions/7539984/асимметричная криптография-пример-в-о-о-о/7540173 # 7540173), которая вдохновила меня на аналогичный подход. Кроме того, по сравнению с криптографическими функциями в предыдущей ссылке, я чувствую, что что-то осталось, даже несмотря на успешное тестирование. – user2320464

+0

Откуда у вас ключи? Вы делаете их самостоятельно через powershell? –

ответ

4

Я знаю, что это старый. Я взял начальную точку, которую вы здесь, и добавил некоторые предметы. Я попытался очистить там, где это уместно, и использовать имена переменных, которые могут помочь сделать вещи немного легче для someonelse, которые читают это, чтобы понять.

Шифрование:

Function Encrypt-Asymmetric { 
[CmdletBinding()] 
[OutputType([System.String])] 
param(
    [Parameter(Position=0, Mandatory=$true)][ValidateNotNullOrEmpty()][System.String] 
    $ClearText, 
    [Parameter(Position=1, Mandatory=$true)][ValidateNotNullOrEmpty()][ValidateScript({Test-Path $_ -PathType Leaf})][System.String] 
    $PublicCertFilePath 
) 
# Encrypts a string with a public key 
$PublicCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($PublicCertFilePath) 
$ByteArray = [System.Text.Encoding]::UTF8.GetBytes($ClearText) 
$EncryptedByteArray = $PublicCert.PublicKey.Key.Encrypt($ByteArray,$true) 
$EncryptedBase64String = [Convert]::ToBase64String($EncryptedByteArray) 

Return $EncryptedBase64String 
} 

дешифрование:

Function Decrypt-Asymmetric 
{ 
[CmdletBinding()] 
[OutputType([System.String])] 
param(
    [Parameter(Position=0, Mandatory=$true)][ValidateNotNullOrEmpty()][System.String] 
    $EncryptedBase64String, 
    [Parameter(Position=1, Mandatory=$true)][ValidateNotNullOrEmpty()][System.String] 
    $CertThumbprint 
) 
# Decrypts text using the private key 
# Assumes the certificate is in the LocalMachine\My (Personal) Store 
$Cert = Get-ChildItem cert:\LocalMachine\My | where { $_.Thumbprint -eq $CertThumbprint } 
if($Cert) { 
    $EncryptedByteArray = [Convert]::FromBase64String($EncryptedBase64String) 
    $ClearText = [System.Text.Encoding]::UTF8.GetString($Cert.PrivateKey.Decrypt($EncryptedByteArray,$true)) 
} 
Else {Write-Error "Certificate with thumbprint: $CertThumbprint not found!"} 

Return $ClearText 
} 

http://grokgarble.com/blog/?p=228

Смежные вопросы