要实现AES加密的C#和Java之间的互通,可以使用以下步骤:
using System;
using System.Security.Cryptography;
using System.Text;
public class AesEncryption
{
public static string Encrypt(string plainText, string key, string iv)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
byte[] encryptedData;
using (var msEncrypt = new System.IO.MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encryptedData = msEncrypt.ToArray();
}
}
return Convert.ToBase64String(encryptedData);
}
}
}
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesDecryption {
public static String Decrypt(String encryptedText, String key, String iv) throws Exception {
byte[] encryptedData = Base64.getDecoder().decode(encryptedText);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedData = cipher.doFinal(encryptedData);
return new String(decryptedData);
}
}
string plainText = "Hello World";
string key = "0123456789ABCDEF";
string iv = "FEDCBA9876543210";
string encryptedText = AesEncryption.Encrypt(plainText, key, iv);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = AesDecryption.Decrypt(encryptedText, key, iv);
System.out.println("Decrypted Text: " + decryptedText);
这样,你就可以在C#和Java之间实现AES加密和解密的互通了。请注意,确保C#和Java中使用的密钥和初始向量(IV)相同,以便正确解密数据。