惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
博客园 - 司徒正美
S
SegmentFault 最新的问题
Jina AI
Jina AI
美团技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell
小众软件
小众软件
WordPress大学
WordPress大学
爱范儿
爱范儿
博客园 - Franky
量子位
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网

博客园 - 筱老邪

2026年读书清单,及java技术的巩固 请求处理 图片转为为流的处理 编码和解码 SHA1签名算法,JAVA和C# 在Java和C#中计算SHA-1哈希 .net5读取xml文件 部署linux 踩坑 多线程 .net知识点 下载文件,204问题 debug和release的web.config分开配置 数据库的索引查找 sql 查询出符合条件的表增加字段 HTTP状态码:400\500 错误代码 - 筱老邪 - 博客园 linq 两个list交集差集处理 rabbitMQ的使用 rabbitMQ的部署安装 sql 游标循环
C#与Java互通AES算法加密解密
筱老邪 · 2023-07-27 · via 博客园 - 筱老邪

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 }