解密AES/OFB/NoPadding

Decrypt AES/OFB/NoPadding

我需要解密使用 C# 中的 AES/OFB/NoPadding 组合编码的内容。这似乎不受本地支持:以下代码不会像

var aes = new AesManaged
{
   Padding = PaddingMode.None,
   Mode = CipherMode.OFB,
   KeySize = 128,
   BlockSize = 128
};

生产:

System.Security.Cryptography.CryptographicException:
Specified cipher mode is not valid for this algorithm.

我能在 SO 上找到的最接近的问题是 this one, which uses BouncyCastle 进行加密:

Public Function DoEncryption(ByVal KeyArray() As Byte, ByVal IVArray() As Byte, ByVal Buffer     As Byte()) As Byte()

    Dim ae As New CipherKeyGenerator()
    ae.Init(New KeyGenerationParameters(New SecureRandom(), 256))
    Dim aesKeyParam As KeyParameter = ParameterUtilities.CreateKeyParameter("AES",     KeyArray)
    Dim aesIVKeyParam As ParametersWithIV = New ParametersWithIV(aesKeyParam, IVArray)
    Dim cipher As IBufferedCipher = CipherUtilities.GetCipher("AES/OFB/NoPadding")
    cipher.Init(True, aesIVKeyParam)
    Dim encrypted() As Byte = cipher.DoFinal(Buffer)
    Return encrypted

End Function

其他问题(如 this one)包含更多信息,但也包含大量自定义代码 - 我宁愿使用 BouncyCastle。谁能帮我解密,或者给我一些有用的文档?

从实际问题的代码来看,触发解密而不是加密的唯一必要步骤是更改 cipher.Init 调用中的布尔参数:

cipher.Init(False, aesIVKeyParam) // False == decryption, True == encryption

C# 中的最后一个片段是

private static byte[] DoDecryption(byte[] keyArray, byte[] ivArray, byte[] encoded)
{
    var aesKeyParam = ParameterUtilities.CreateKeyParameter("AES", keyArray);
    var aesIvKeyParam = new ParametersWithIV(aesKeyParam, ivArray);
    var cipher = CipherUtilities.GetCipher("AES/OFB/NOPADDING");
    cipher.Init(false, aesIvKeyParam);
    var decrypted = cipher.DoFinal(encoded);
    return decrypted;
}