Home > Mobile >  How to AES decrypt a string in Powershell with a given IV and key as string?
How to AES decrypt a string in Powershell with a given IV and key as string?

Time:02-04

I need to create a powershell code which sould decode an AES-128-CBC-encrypted string. It needs to work with an IV and key in string-format. Here is a demo with sample dataset from a public webpage:

# test-data from https://www.coderstool.com/aes-decryption
# should return 'CodersTool secret message'

$data = "Y egIFaYXtHdRKFVg5h80Bn/6dECi5iiPgr2L9Bd8LY="
$iv   = "rwj76dfsotja10tk"
$key  = "nszxnqbq1s"

$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key = [byte[]][char[]]$key
$aes.IV  = [byte[]][char[]]$IV
$aes.Padding = [System.Security.Cryptography.PaddingMode]::None
$dec = $aes.CreateDecryptor()
$result = $dec.TransformFinalBlock($data, 0, $data.Length)
$dec.Dispose()

But this code throws an error, that the key does not have the correct length. What needs to be fixed to make the above sample work in Powershell and return the expected result?

My final goal is creating a Powershell demo that can convert the content of a DLC-file into cleartext as seen in this js-code: https://github.com/luii/dlc/blob/master/index.js which uses a function crypto.createDecipheriv('AES-128-CBC', key, iv).

CodePudding user response:

The ciphertext has been generated using AES-128 in CBC mode and PKCS#7 padding. The following must be changed in the code:

  • the ciphertext must be Base64 decoded,
  • the key must be padded from right with 0x00 values to a length of 16 bytes (AES-128),
  • the padding must be PKCS#7 (since PKCS#7 is the default, the line can be omitted),
  • the result has to be decoded with UTF-8.

The mode is set correctly, because CBC is the default:

$data = [Convert]::FromBase64String("Y egIFaYXtHdRKFVg5h80Bn/6dECi5iiPgr2L9Bd8LY=")
$iv   = "rwj76dfsotja10tk"
$key  = "nszxnqbq1s".PadRight(16, [char]0)
$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key = [byte[]][char[]]$key
$aes.IV  = [byte[]][char[]]$IV
#$aes.Padding = [System.Security.Cryptography.PaddingMode]::none # change to PKCS7 or omit line, since PKCS7 is the default
$dec = $aes.CreateDecryptor()
$result = $dec.TransformFinalBlock($data, 0, $data.Length)
$resultStr = [Text.Encoding]::Utf8.GetString($result)
Write-Output $resultStr
$dec.Dispose()

Output:

CodersTool secret message
  • Related