Powershell-使用密钥进行密码加密/解密



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

我的代码

#Encryption
$KeyStoragePath="C:TempPassword"
$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:TempPassword"
$CredentialsFileName = "sec-string"
$PasswordSecureString = Read-Host -AsSecureString
$PasswordSecureString | ConvertFrom-SecureString -key $GetKey | Out-File -FilePath "$CredentialsStoragePath$CredentialsFileName"

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

#Decrypt
$MyPasswordFile = "C:TempPasswordsec-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

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

#Encryption
$KeyStoragePath="C:TempPassword"
$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:TempPassword"
$CredentialsFileName = "sec-string"
$PasswordSecureString = Read-Host -AsSecureString
$PasswordSecureString | ConvertFrom-SecureString -key $GetKey | Out-File -FilePath "$CredentialsStoragePath$CredentialsFileName"
#Decrypt
$MyPasswordFile = "C:TempPasswordsec-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)

最新更新