When i'm trying to encrypt a 50 character string, using the System.Security.Cryptography.RSACryptoServiceProvider object I get a bad length error when calling encrypt. My educated guess is that the length of the string is too much (maybe limitation of [byte]?), because when I have a 39char string everything works fine.
Full errors below:
Exception calling "Encrypt" with "2" argument(s): "Bad Length. "At [omitted]
+ $encrypted = $rsa.Encrypt($bytes,$true) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CryptographicExceptionException calling "Decrypt" with "2" argument(s): "Error occurred while decoding OAEP padding." At [omitted] + $Password = [char[]]$rsa.Decrypt($encrypted, $true) -join "" | Co ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : CryptographicException
My code:
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 }
Modulus size -2 -2*hLen, where hLen is the size of the hash.I hope you know what that means. - mklement0