【问题标题】:Decrypt AES/OFB/NoPadding解密 AES/OFB/NoPadding
【发布时间】:2019-11-01 23:02:55
【问题描述】:

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

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

生产:

System.Security.Cryptography.CryptographicException:
指定的密码模式对此算法无效。

我可以在 SO 上找到的最接近的问题是 this one,它使用 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。谁能帮我解密,或者给我一些有用的文档?

【问题讨论】:

  • "BouncyCastle C# APIs",没有 C# API 和 VB.NET API,这不是 .NET 的工作方式。如果您要问如何将 VB.NET 代码转换为 C# 代码,甚至可以在几秒钟内在线完成此操作
  • 感谢在线转换@CamiloTerevinto 的指针。我也更新了我的问题,以更多地反映我的需要并消除您指出的错误二分法。
  • 你添加的代码与VB.NET版本的相似如何?您的更新反映您不理解我的评论
  • 感谢您的补充评论@CamiloTerevinto :) 我添加了代码来展示我自己尝试实现的目标 - 它并不意味着类似于下面的 VB 代码,而只是为了提供更多我的问题的上下文。
  • 第 1 步:转到this site。第 2 步:选择 VB.NET > C#。第 3 步:粘贴 VB.NET 代码。第 4 步:将 C# 代码复制到您的项目中。我看不出这里有什么困难

标签: c# asp.net-core encryption aes bouncycastle


【解决方案1】:

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

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

C#中最终的sn-p是

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2014-08-22
    • 2021-12-30
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多