gpt4 book ai didi

java - AES 256 java 和 .Net 兼容加密和解密?

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

我想使用 Java 和 .Net 进行 AES 256 加密/解密。这意味着我应该能够使用 Java 加密并使用 .Net 和 Vice vesra 解密。以下是 Java AES 256 加密。

byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
return new String(Base64.encodeBase64(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));

最佳答案

1) Java 解密部分由下式给出

byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
return new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt.getBytes("UTF-8"))));

哪里strToDecrypt是Base64编码的加密数据(由加密部分的返回值给出),仅最后两行与加密部分有偏差。

注意:实际上,IV 应随机生成(例如 Generating random IV for AES in Java )。但我认为这很清楚,0 序列仅用于测试目的。

2)关于 key 派生PBKDF2WithHmacSHA256 C# 解决方案取决于您的 .NET 框架版本。对于 V4.7.2 及更高版本,可以通过以下方式导出 key :

// .NET Framework 4.7.2 +
byte[] secretKey = null;
using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(KEY, Encoding.UTF8.GetBytes(SALT), 65536, HashAlgorithmName.SHA256))
{
secretKey = rfc2898.GetBytes(32);
}

注意: Rfc2898DeriveBytes 的先前实现(v4.7.2 之前)使用SHA1 (硬编码)而不是 SHA256因此,没有 ctor 需要 4 个参数。此外,Rfc2898DeriveBytes -class 要求 salt-length 至少为 8 个字节,否则 System.ArgumentException: Salt is not at least eight bytes被抛出。

另一种选择是:

// .NET Framework 4.5 + 
byte[] secretKey = null;
KeyDerivationPrf keyDerivationPrf = KeyDerivationPrf.HMACSHA256;
secretKey = KeyDerivation.Pbkdf2(KEY, Encoding.UTF8.GetBytes(SALT), keyDerivationPrf, 65536, 32);

后者适用于 V4.6.1 及更高版本,但您需要 Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivation - 类哪个你可以找到例如在https://www.nuget.org/packages/Microsoft.AspNetCore.Cryptography.KeyDerivation/ 。对于安装,您可以使用例如包管理器控制台(工具 - NuGet 包管理器 - 包管理器控制台)。只需按照链接中的说明输入相应的命令即可。也许您会收到 IDE 错误 CS0012 。在这种情况下,您必须添加 <Reference Include="netstandard" />到您的csproj的引用部分-file(另请参阅 https://github.com/dotnet/standard/issues/542 )。 KeyDerivationPrf -class 不限制盐长度。

还有其他可能性(例如 Bouncy CaSTLe),我没有尝试过,但也许它们对您来说是更好的选择。此主题也在 Rfc2898 / PBKDF2 with SHA256 as digest in c# 中进行了讨论。 .

3) C# 加密方法的示例是:

public string Encrypt(string plainText)
{
// PBKDF2WithHmacSHA256 Key derivation
// ...

using (RijndaelManaged cipher = new RijndaelManaged())
{
cipher.Key = secretKey;
cipher.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;

byte[] encryptedData;
using (ICryptoTransform encryptor = cipher.CreateEncryptor())
{
using (System.IO.MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(plainText);
}
encryptedData = memoryStream.ToArray();
}
}
}

return Convert.ToBase64String(encryptedData);
}
}

哪里plainText是包含纯文本的字符串(对应于 strToEncrypt )。加密的数据进行 Base64 编码并以字符串形式返回(类似于 Java 方法)。

测试用例:

String KEY = "The Password";
String SALT = "The Salt";
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

给出

Plain text:       This is a plain text that needs to be encrypted
Key (hex): 2D7664713D701C58FC506F93CEA3194671AD3B5C034255A4AC04AF46EADC89BC
Base64 encoded
encrypted data: ksUYjmbP9ga39LXr3wXQ34Bp32UlloYPxg3WWuW0iovWbg/GxHJrIuF3jrDvjr/Q

4) C# 解密方法的示例是:

public string Decrypt(string encryptedText)
{
// PBKDF2WithHmacSHA256 Key derivation
// ...

using (RijndaelManaged cipher = new RijndaelManaged())
{
cipher.Key = secretKey;
cipher.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;

string decryptedText;
using (ICryptoTransform decryptor = cipher.CreateDecryptor())
{
using (System.IO.MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(encryptedText)))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader(cryptoStream))
{
decryptedText = streamReader.ReadToEnd();
}
}
}
}

return decryptedText;
}
}

哪里encryptedText是加密部分的返回值(base64编码的加密数据,对应 strToDecrypt )。该方法返回解密的文本(类似于 Java 方法)。

关于java - AES 256 java 和 .Net 兼容加密和解密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54069449/

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