.NET与Java互通AES算法加密解密
2024-08-31 22:14:07
/// <summary>AES加密</summary>
/// <param name="text">明文</param>
/// <param name="key">密钥,长度为16的字符串</param>
/// <param name="iv">偏移量,长度为16的字符串</param>
/// <returns>密文</returns>
public static string EncodeAES(string text, string key,string iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.Zeros;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
} /// <summary>AES解密</summary>
/// <param name="text">密文</param>
/// <param name="key">密钥,长度为16的字符串</param>
/// <param name="iv">偏移量,长度为16的字符串</param>
/// <returns>明文</returns>
public static string DecodeAES(string text, string key,string iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.Zeros;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(text);
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length)
len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
上面代码为C# 需要引用System.Security.Cryptography命名空间
Java,需要以下引用:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
另外需要对String和byte[]相互转换的类,我自己写的Base64Helper
/**
* @author miracle.qu
* @see AES算法加密明文
* @param data 明文
* @param key 密钥,长度16
* @param iv 偏移量,长度16
* @return 密文
*/
public static String encryptAES(String data,String key,String iv) throws Exception {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
} byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext); return Base64Helper.encode(encrypted).trim(); } catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* @author miracle.qu
* @see AES算法解密密文
* @param data 密文
* @param key 密钥,长度16
* @param iv 偏移量,长度16
* @return 明文
*/
public static String decryptAES(String data,String key,String iv) throws Exception {
try
{
byte[] encrypted1 = Base64Helper.decode(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString.trim();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
其中Base64Helper类是个简单的类,引用:
import org.apache.commons.codec.binary.Base64;
/**
* 编码
* @param byteArray
* @return
*/
public static String encode(byte[] byteArray) {
return new String(new Base64().encode(byteArray));
} /**
* 解码
* @param base64EncodedString
* @return
*/
public static byte[] decode(String base64EncodedString) {
return new Base64().decode(base64EncodedString);
}
摘抄 :http://blog.csdn.net/mr_qu/article/details/8433370
https://en.wikipedia.org/wiki/Initialization_vector
最新文章
- SQL Server 合并复制遇到identity range check报错的解决
- AnjularJS异步编程 Promise和$q
- 简单使用Apache POI
- Bootstrap中glyphicons-halflings-regular.woff字体报404错notfound
- Linux 下新增虚拟内存
- Eclipse中项目面板字体的修改
- 如何将XSD文件以及引入import的文件生成相应的C#类。
- Android滑动菜单框架完全解析,教你如何一分钟实现滑动菜单特效
- CSDN 四川大学线下编程比赛第二题:Peter的X
- Objective-C运行时态消息传递--拼接方法名
- JS中的函数和BOM
- Python+Selenium基础篇之1-环境搭建
- [Django]bulk_create 探究
- 压力测试工具ab - Apache HTTP server benchmarking tool
- bottle.py中的SimpleTemplate
- px与rem的换算
- 如何建一个maven项目
- Python之旅Day1 数据类型初识(数字|字符串|列表|数据运算) 编码 表达式(if...else|for|while)
- LeetCode——Binary Tree Paths
- strlen与sizeof区别