Search code examples
c#powershellcryptographybouncycastle

Output buffer too short Message when using BouncyCastle Crypto in Powershell / C#


When I try to encrypt a string using Bouncycastle V1.8.5 (aes256, gcm, nopadding), I get the Error Message

Exception calling "DoFinal" with "2" argument(s): "Output buffer too short"

My Code:

Add-Type -Path "C:\Program Files\PackageManagement\NuGet\Packages\BouncyCastle.1.8.5\lib\BouncyCastle.Crypto.dll"
$secretmessage = "Totalgeheim!"
$secretmessageBytes = [System.Text.Encoding]::UTF8.GetBytes($secretmessage)
$bytes = [system.byte[]]::CreateInstance([System.Byte],16)
[System.Security.Cryptography.RNGCryptoServiceProvider]::new().GetNonZeroBytes($bytes)
$key = $bytes
$bytes = [system.byte[]]::CreateInstance([System.Byte],8)
([System.Security.Cryptography.RNGCryptoServiceProvider]::new()).GetNonZeroBytes($bytes)
$salt = $bytes
[byte]$nonSecretPayload = $null
$cipher = [Org.BouncyCastle.Crypto.Modes.GcmBlockCipher]::new([Org.BouncyCastle.Crypto.Engines.AesEngine]::new())
$parameters = [Org.BouncyCastle.Crypto.Parameters.AeadParameters]::new([Org.BouncyCastle.Crypto.Parameters.KeyParameter]::new($key), 128, $salt, $nonSecretPayload) #payload als byte!!!
$cipher.Init($true, $parameters)
$ciphertext = [System.Text.Encoding]::UTF8.GetBytes($cipher.GetOutputSize($secretmessageBytes.Length))
$len = $cipher.ProcessBytes($secretmessageBytes, 0, $secretmessageBytes.Length, $ciphertext, 0)
$cipher.DoFinal($ciphertext, $len)

Does anyone has an idea, why this is not working as expected?


Solution

  • $cipher.GetOutputSize() will output the byte-length as an integer - passing it to UTF8Encoding.GetBytes(), implicitly converting it to a string, will result in an array of only a few bytes.

    Replace this line:

    $ciphertext = [System.Text.Encoding]::UTF8.GetBytes($cipher.GetOutputSize($secretmessageBytes.Length))
    

    ... with:

    $ciphertext = [byte[]]::new($cipher.GetOutputSize($secretmessageBytes.Length))
    

    If your script needs to run on versions older than PowerShell 5.0, use New-Object or Array.CreateInstance() instead:

    $cipherText = [array]::CreateInstance([byte], $cipher.GetOutputSize($secretmessageBytes.Length))
    # or 
    $cipherText = New-Object 'byte[]' -ArgumentList $cipher.GetOutputSize($secretmessageBytes.Length)