Home > Net >  PowerShell: convertfrom-securestring -securekey
PowerShell: convertfrom-securestring -securekey

Time:09-02

I am trying to use convertfrom-securestring with the parameter -securekey. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertfrom-securestring?view=powershell-7.2

  1. Create ByteArray
 $length = 256
 $byte = $length / 8
 $key = New-Object Byte[] $byte
 $null = [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($key)
  1. Convert ByteArray to String and convert String to SecureString
$keyString = [System.BitConverter]::ToString($key)
$secureKeyString = convertto-securestring $keyString -asPlainText -force
  1. Finally use secureString as secureKey
convertfrom-securestring (convertto-securestring "stringToProtect" -asplaintext -force) -secureKey $secureKeyString

Exception: the specified key is not valid. Valid key length settings are either 128 bits, 192 bits, or 256 bits.

I tried several other ways to convert the byte array to string, e.g.:

[System.Text.Encoding]::ASCII.GetString($Key)

But in the end I always get the same exception. Anyone knows what I am doing wrong?

Cheers

CodePudding user response:

[System.BitConverter]::ToString($key) creates human-readable representation of the byte array stored in $key - which is not what you want - you want a string whose encoded representation is bit-for-bit the same as the key.

So instead, convert the $key array to a string with UnicodeEncoding.GetString() and use that to construct the [securestring] representation:

$secureKey = [securestring]::new()
foreach($char in [System.Text.Encoding]::Unicode.GetString($key).ToCharArray()){
    $secureKey.AppendChar($char)
}

$secureKey now points to an internal string that's exactly 32 bytes - or 256 bits - wide, usable as a key:

ConvertFrom-SecureString ("plainText" |ConvertTo-SecureString -AsPlainText -Force) -SecureKey $secureKey
  • Related