从.NET到Java的AES-256解密过程涉及到几个关键步骤,包括确保两端使用相同的加密算法、密钥、初始化向量(IV)以及填充方式。以下是一个详细的步骤指南和示例代码,帮助你完成从.NET加密的数据在Java中的解密。
假设你在.NET端已经有了加密的数据,以下是一个加密示例:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryption
{
private static readonly byte[] Salt = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };
public static byte[] Encrypt(string plainText, byte[] key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = GenerateIV();
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
return msEncrypt.ToArray();
}
}
}
}
private static byte[] GenerateIV()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] iv = new byte[16];
rng.GetBytes(iv);
return iv;
}
}
}
以下是一个Java端的解密示例,用于解密.NET端加密的数据:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesDecryption {
private static final byte[] SALT = new byte[]{(byte) 0x26, (byte) 0xdc, (byte) 0xff, (byte) 0x00, (byte) 0xad, (byte) 0xed, (byte) 0x7a, (byte) 0xee, (byte) 0xc5, (byte) 0xfe, (byte) 0x07, (byte) 0xaf, (byte) 0x4d, (byte) 0x08, (byte) 0x22, (byte) 0x3c};
public static String decrypt(String encryptedText, byte[] key) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] iv = new byte[16];
System.arraycopy(encryptedBytes, 0, iv, 0, 16);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes, 16, encryptedBytes.length - 16);
return new String(decryptedBytes);
}
public static void main(String[] args) {
try {
String encryptedText = "..."; // 从.NET端获取的加密文本
byte[] key = "...".getBytes("UTF-8"); // 确保与.NET端使用的密钥相同
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过以上步骤和示例代码,你应该能够成功地在Java端解密从.NET端加密的数据。
领取专属 10元无门槛券
手把手带您无忧上云