C#与Java互通AES算法加密解密

C# 需要引用System.Security.Cryptography命名空间

复制代码
 1 /// <summary>AES加密</summary>
 2 
 3 /// <param name="text">明文</param>
 4 /// <param name="key">密钥,长度为16的字符串</param>
 5 /// <param name="iv">偏移量,长度为16的字符串</param>
 6 /// <returns>密文</returns>
 7 public static string EncodeAES(string text, string key,string iv)
 8 {
 9     RijndaelManaged rijndaelCipher = new RijndaelManaged();
10     rijndaelCipher.Mode = CipherMode.CBC;
11     rijndaelCipher.Padding = PaddingMode.Zeros;
12     rijndaelCipher.KeySize = 128;
13     rijndaelCipher.BlockSize = 128;
14     byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
15     byte[] keyBytes = new byte[16];
16     int len = pwdBytes.Length;
17     if (len > keyBytes.Length)
18         len = keyBytes.Length;
19     System.Array.Copy(pwdBytes, keyBytes, len);
20     rijndaelCipher.Key = keyBytes;
21     rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);
22     ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
23     byte[] plainText = Encoding.UTF8.GetBytes(text);
24     byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
25     return Convert.ToBase64String(cipherBytes);
26 }
27  
28 /// <summary>AES解密</summary>
29 /// <param name="text">密文</param>
30 /// <param name="key">密钥,长度为16的字符串</param>
31 /// <param name="iv">偏移量,长度为16的字符串</param>
32 /// <returns>明文</returns>
33 public static string DecodeAES(string text, string key,string iv)
34 {
35     RijndaelManaged rijndaelCipher = new RijndaelManaged();
36     rijndaelCipher.Mode = CipherMode.CBC;
37     rijndaelCipher.Padding = PaddingMode.Zeros;
38     rijndaelCipher.KeySize = 128;
39     rijndaelCipher.BlockSize = 128;
40     byte[] encryptedData = Convert.FromBase64String(text);
41     byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
42     byte[] keyBytes = new byte[16];
43     int len = pwdBytes.Length;
44     if (len > keyBytes.Length)
45         len = keyBytes.Length;
46     System.Array.Copy(pwdBytes, keyBytes, len);
47     rijndaelCipher.Key = keyBytes;
48     rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);
49     ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
50     byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
51     return Encoding.UTF8.GetString(plainText);
52 }
复制代码

 

 
Java,需要以下引用:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

另外需要对String和byte[]相互转换的类,我自己写的Base64Helper

复制代码
 1 /**
 2 
 3  * @author miracle.qu
 4  * @see AES算法加密明文
 5  * @param data 明文
 6  * @param key 密钥,长度16
 7  * @param iv 偏移量,长度16
 8  * @return 密文
 9  */
10   public static String encryptAES(String data,String key,String iv) throws Exception {
11         try {
12             Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
13             int blockSize = cipher.getBlockSize();
14             byte[] dataBytes = data.getBytes();
15             int plaintextLength = dataBytes.length;
16              
17             if (plaintextLength % blockSize != 0) {
18                 plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
19             }
20  
21             byte[] plaintext = new byte[plaintextLength];
22             System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
23               
24             SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
25             IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
26  
27             cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
28             byte[] encrypted = cipher.doFinal(plaintext);
29  
30             return Base64Helper.encode(encrypted).trim();
31  
32         } catch (Exception e) {
33             e.printStackTrace();
34             return null;
35         }
36     }
37  
38     /**
39      * @author miracle.qu
40      * @see AES算法解密密文
41      * @param data 密文
42      * @param key 密钥,长度16
43      * @param iv 偏移量,长度16
44      * @return 明文
45      */
46     public static String decryptAES(String data,String key,String iv) throws Exception {
47         try
48         {
49             byte[] encrypted1 = Base64Helper.decode(data);
50               
51             Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
52             SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
53             IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
54               
55             cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
56  
57             byte[] original = cipher.doFinal(encrypted1);
58             String originalString = new String(original);
59             return originalString.trim();
60         }
61         catch (Exception e) {
62             e.printStackTrace();
63             return null;
64         }
65     }
复制代码

 

 其中Base64Helper类是个简单的类,引用:

 

import org.apache.commons.codec.binary.Base64;

 

其中核心代码:

复制代码
 1 /**
 2 
 3  * 编码
 4  * @param byteArray
 5  * @return
 6  */
 7 public static String encode(byte[] byteArray) {
 8     return new String(new Base64().encode(byteArray));
 9 }
10  
11 /**
12  * 解码
13  * @param base64EncodedString
14  * @return
15  */
16 public static byte[] decode(String base64EncodedString) {
17     return new Base64().decode(base64EncodedString);
18 }
复制代码

 

posted @   筱老邪  阅读(486)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示