【问题标题】:Output buffer too short Message when using BouncyCastle Crypto in Powershell / C#在 Powershell / C# 中使用 BouncyCastle Crypto 时输出缓冲区太短消息
【发布时间】:2020-03-05 00:25:01
【问题描述】:

当我尝试使用 Bouncycastle V1.8.5(aes256、gcm、nopadding)加密字符串时,我收到错误消息

使用“2”参数调用“DoFinal”的异常:“输出缓冲区太短”

我的代码:

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)

有谁知道,为什么这没有按预期工作?

【问题讨论】:

  • 填充模式不同。 Java 和 Net 库中的默认填充不同。

标签: c# powershell cryptography bouncycastle


【解决方案1】:

$cipher.GetOutputSize() 会将字节长度作为整数输出 - 将其传递给 UTF8Encoding.GetBytes(),将其隐式转换为字符串,将生成一个只有几个字节的数组。

替换这一行:

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

...与:

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

如果您的脚本需要在早于 PowerShell 5.0 的版本上运行,请改用 New-ObjectArray.CreateInstance()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多