Skip to content

Instantly share code, notes, and snippets.

@nickadam
Created April 2, 2022 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickadam/eff6a1c2193fbeb77972c05589efd862 to your computer and use it in GitHub Desktop.
Save nickadam/eff6a1c2193fbeb77972c05589efd862 to your computer and use it in GitHub Desktop.
Decrypt Rijndael 256 blocks in PowerShell Core with BouncyCastle
$Key = "SomeKey"
$IV = "SomeIV"
$CipherText = "eeXS+8jW/xrgFFeWdykzm0t8F6pmbuQwjU2uLfqJA+KyLaozbzkJ5zkpzmREA2XevE87kJXaisRDFJNeXkg+Lw=="
# Base64 CipherText to ByteArray
$CipherBytes = [System.Convert]::FromBase64String($CipherText) -As [byte[]]
# Get the Bytes of the Key and IV
$KeyBytes = [System.Text.Encoding]::UTF8.GetBytes($Key)
$IvBytes = [System.Text.Encoding]::UTF8.GetBytes($Iv)
# Load BouncyCastle
[Reflection.Assembly]::LoadFile((Get-Item .\BouncyCastle.Crypto.dll).FullName) | Out-Null
# Create decryptor
$Engine = [Org.BouncyCastle.Crypto.Engines.RijndaelEngine]::New(256)
$BlockCipher = [Org.BouncyCastle.Crypto.Modes.CbcBlockCipher]::New($Engine)
$Padding = [Org.BouncyCastle.Crypto.Paddings.ZeroBytePadding]::New()
$Cipher = [Org.BouncyCastle.Crypto.Paddings.PaddedBufferedBlockCipher]::New($BlockCipher, $Padding)
$KeyParam = [Org.BouncyCastle.Crypto.Parameters.KeyParameter]::New($KeyBytes)
$KeyParamWithIV = [Org.BouncyCastle.Crypto.Parameters.ParametersWithIV]::New($KeyParam, $IvBytes)
$Cipher.Init($False, $KeyParamWithIV)
# Create Byte array of appropriate length to store decryted data
$ComparisonBytes = [System.Byte[]]::CreateInstance([System.Byte], $Cipher.GetOutputSize($CipherBytes.Length))
# Decrypt
$Length = $Cipher.ProcessBytes($CipherBytes, $ComparisonBytes, 0)
$Cipher.DoFinal($ComparisonBytes, $Length) | Out-Null
# Find the end of the decrypted string, zero padding
$DecryptLength = $ComparisonBytes.Length
While(0 -eq $ComparisonBytes[$DecryptLength - 1]){
$DecryptLength--
}
# Output decrypted string
[System.Text.Encoding]::UTF8.GetString($ComparisonBytes, 0, $DecryptLength)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment