【发布时间】:2016-07-22 06:46:02
【问题描述】:
当我尝试使用 System.Security.Cryptography.RSACryptoServiceProvider 对象加密 50 个字符的字符串时,调用 encrypt 时出现错误长度错误。 我有根据的猜测是字符串的长度太大(可能是 [byte] 的限制?),因为当我有一个 39char 字符串时,一切正常。
以下完整错误:
使用“2”个参数调用“加密”的异常:“长度错误。 "在[省略]
+ $encrypted = $rsa.Encrypt($bytes,$true) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CryptographicException使用“2”参数调用“解密”的异常:“解码 OAEP 填充时发生错误。” 在[省略] + $Password = [char[]]$rsa.Decrypt($encrypted, $true) -join "" |共... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CryptographicException
我的代码:
function Checkpassword([String] $Type) {
$pwpath = "$root\$Type.pw"
$encrypted = ''
if (test-path $pwpath -erroraction silentlycontinue) {
$encrypted = Import-Clixml $pwpath
}
if(!($encrypted)) {
write-host "No $Type password file found, create one now by entering your $Type password." -fore yellow
# Create password file using local encryption
$key = (2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43,6,6,6,6,6,6,31,33,60,23)
$pass = Read-Host "Enter your $Type password" -AsSecureString
$securepass = $pass |ConvertFrom-SecureString -Key $key
$bytes = [byte[]][char[]]$securepass
$csp = New-Object System.Security.Cryptography.CspParameters
$csp.KeyContainerName = "SuperSecretProcessOnMachine"
$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp
$rsa.PersistKeyInCsp = $true
$encrypted = $rsa.Encrypt($bytes,$true)
$encrypted |Export-Clixml "$root\$Type.pw" -force
}
$key = (2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43,6,6,6,6,6,6,31,33,60,23)
$csp = New-Object System.Security.Cryptography.CspParameters
$csp.KeyContainerName = "SuperSecretProcessOnMachine"
$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp
$rsa.PersistKeyInCsp = $true
$Password = [char[]]$rsa.Decrypt($encrypted, $true) -join "" |ConvertTo-SecureString -Key $key
$credential = New-Object System.Management.Automation.PsCredential ".",$Password }
【问题讨论】:
-
docs 提到了与 OAEP 填充结合使用时输入字节数组的大小限制,描述如下:
Modulus size -2 -2*hLen, where hLen is the size of the hash.我希望您知道这意味着什么。
标签: powershell password-encryption