powershell - 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
解决方案
在正确的地方使用正确的东西。您应该使用密钥解密密码
#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)
推荐阅读
- c++ - 数组c ++中的有理数
- python-imaging-library - PIL 中的 ImagingMemoryInstance 结构体的细化
- python - 如何在图中找到先决条件的总数
- blazor - 使用 bUnit 和 Moq 测试使用 Fluxor 的剃须刀组件
- python - 基于比较两个数据框 [Python],使用 Pandas 生成 3D“矩阵”
- elasticsearch - 使用 logstash 同时将数据插入两个不同的 Elasticsearch 索引
- html - HTML 包含多少种类型的标题?
- flutter - 电话包构建失败
- php - include_once 在 php 脚本上导致 505
- typescript - 如何发布包含 CSS 模块的基于 TypeScript 的 npm 模块?