本篇文章详细介绍了如何在Java项目中使用AES算法进行数据加密和解密的具体方法,并提供了相应的代码示例。适合需要增强应用安全性的开发者阅读参考。
最近编写了一些加密解密的代码,并参考了许多文章结合自己的理解后将代码发布出来供他人参考。
```java
import javax.crypto.*;
import javax.crypto.spec.*;
public class AES {
public static void main(String[] args) throws Exception {
// 加密用的Key,可以由26个字母和数字组成,最好不使用保留字符。
String cKey = 1234567890abcDEF;
// 需要加密的字串
String cSrc = 我的MSN:xxxx@hotmail.com,QQ:10000;
long lStart = System.currentTimeMillis();
String enString = AES.Encrypt(cSrc, cKey);
System.out.println(加密后的字串是: + enString);
long lUseTime = System.currentTimeMillis() - lStart;
System.out.println(加密耗时: + lUseTime + 毫秒);
// 解密
lStart = System.currentTimeMillis();
String deString = AES.Decrypt(enString, cKey);
System.out.println(解密后的字串是: + deString);
lUseTime = System.currentTimeMillis() - lStart;
System.out.println(解密耗时: + lUseTime + 毫秒);
}
public static String Decrypt(String sSrc, String sKey) throws Exception {
try {
if (sKey == null) {
return null;
}
if (sKey.length() != 16) {
return null;
}
byte[] raw = sKey.getBytes(ASCII);
SecretKeySpec keySpec = new SecretKeySpec(raw, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
return null;
}
if (sKey.length() != 16) {
return null;
}
byte[] raw = sKey.getBytes(ASCII);
SecretKeySpec keySpec = new SecretKeySpec(raw, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return byte2hex(encrypted).toLowerCase();
}
public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for(int i=0;i != l/2 ;i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
}
return b;
}
public static String byte2hex(byte[] b) {
String hs = ;
for(int n=0;n