gpt4 book ai didi

c# - AES 解密 - 将代码从 C# 移植到 Java

转载 作者:行者123 更新时间:2023-11-30 22:22:02 24 4
gpt4 key购买 nike

我正在尝试将以下代码从 C# 移植到 Java。我多次尝试尝试解密我的加密数据,但每次都出现乱码。下面的代码使用 org.bouncycaSTLe 库,不幸的是,C# 代码和 Java 代码之间似乎没有一对一的映射。

我基本上知道三件事:

  • byte[] 文件 - 这包含我的加密文件。通常是一个相当大的字节数组。
  • byte[] 填充 - 每次都是 32*bytes*,似乎前 16 个字节用作 IV。
  • byte[] aesKey - 每次都是 32*bytes*,我不知道 C# 代码是如何使用这个数组的。

原始 C# 代码

    private byte[] decryptmessage(byte[] cmessage, byte[] iVector, byte[] m_Key)
{
{
//// randomly generated number acts as inetialization vector
m_IV = new byte[16];
Array.Copy(iVector, 0, m_IV, 0, 16);

// GenerateAESKey();
KeyParameter aesKeyParam = ParameterUtilities.CreateKeyParameter("AES", m_Key);
ParametersWithIV aesIVKeyParam = new ParametersWithIV(aesKeyParam, m_IV);

IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CFB/NoPadding");
cipher.Init(false, aesIVKeyParam);
return cipher.DoFinal(cmessage);
}
}

我在Java中的尝试

  private static byte[] decryptMessage(byte[] file, byte[] iVector, byte[] aesKey) throws Exception {
IvParameterSpec spec = new IvParameterSpec(Arrays.copyOfRange(iVector, 0, 16));
SecretKeySpec key = new SecretKeySpec(Arrays.copyOfRange(aesKey, 0, 16), "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, spec);
return cipher.doFinal(file);
}

P.S:这是解密的最后一步。在此之前,我必须从我的加密文件中取出一些初始字节集,并使用 RSA 私钥对其进行解密以获取此 AES key 。

如果有人有我可以阅读的链接/文档,它正确解释了使用 AES 加密文件的整个过程,然后在 key 上使用 RSA 和 iv 到加密文件的开头,我将非常高兴。我一直在盯着 C# 代码看,我想看一些带图片的东西。

编辑:字节不是位。

EDIT2:为了一致性和正确性,将 padding 重命名为 iVector。

最佳答案

在 C# 代码中,您使用 256 位(32 字节)初始化 key ,从而获得 AES-256。在 Java 代码中,您只使用 128 位(16 字节)并获得 AES-128。

所以修复可能是:

SecretKeySpec key = new SecretKeySpec(aesKey, "AES");

然后您可能会发现 Java 不想使用 256 位 key (出于法律原因)。然后你必须安装 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6 .

关于c# - AES 解密 - 将代码从 C# 移植到 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14022343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com