最近写一些加密解密的代码,找了不少的文章,结合自己的理解,现把我写的代码 POST
出来,供大家参考。
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 = "Email : xxx@xxx.com"
;
//加密
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 {
//判断 Key 是否正确
if (sKey == null) {
System.out.print("Key 为空 null");
return null;
}
//判断 Key 是否为 16 位
if (sKey.length() != 16) {
System.out.print("Key 长度不是 16 位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
评论16