首页 > 解决方案 > Powershell - 使用密钥加密/解密密码

问题描述

我正在尝试使用 powershell 加密和解密密码。但是无法成功解密

我的代码

#Encryption
$KeyStoragePath="C:\Temp\Password"
$KeyFileName="AESKey.AES.Key"
$CreateKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($CreateKey)
$CreateKey | out-file ".\$KeyFileName"

$GetKey = Get-Content "$KeyStoragePath\$KeyFileName"
$CredentialsStoragePath = "C:\Temp\Password\"
$CredentialsFileName = "sec-string"
$PasswordSecureString = Read-Host -AsSecureString
$PasswordSecureString | ConvertFrom-SecureString -key $GetKey | Out-File -FilePath "$CredentialsStoragePath\$CredentialsFileName"

这成功地创建了一个包含安全字符串的安全文件。但是,无法使用密钥对其进行解密。

#Decrypt

$MyPasswordFile = "C:\Temp\Password\sec-string"

$MyPassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $CreateKey

错误

$MyPassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $CreateKey
ConvertTo-SecureString : Padding is invalid and cannot be removed.
At line:1 char:43
+ $MyPassword = Get-Content $PasswordFile | ConvertTo-SecureString -Key $CreateKey
+                                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
    + FullyQualifiedErrorId : ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

标签: powershellencryption

解决方案


在正确的地方使用正确的东西。您应该使用密钥解密密码

#Encryption
$KeyStoragePath="C:\Temp\Password"
$KeyFileName="AESKey.AES.Key"
$CreateKey = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($CreateKey)
$CreateKey | out-file "$KeyStoragePath\$KeyFileName"

$GetKey = Get-Content "$KeyStoragePath\$KeyFileName"
$CredentialsStoragePath = "C:\Temp\Password\"
$CredentialsFileName = "sec-string"
$PasswordSecureString = Read-Host -AsSecureString
$PasswordSecureString | ConvertFrom-SecureString -key $GetKey | Out-File -FilePath "$CredentialsStoragePath\$CredentialsFileName"

#Decrypt

$MyPasswordFile = "C:\Temp\Password\sec-string"


$MyPassword = Get-Content $MyPasswordFile | ConvertTo-SecureString -Key $GetKey


# Additional code below will change to plain text but this is bad practice. You should not need the plaintext password. You can create a credential from the secure string

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MyPassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

推荐阅读