僅做記錄,非原創(chuàng)
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author hman
*
*/
public class AESUtil {
// 加密
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key為空null");
return null;
}
// 判斷Key是否為16位
if (sKey.length() != 16) {
System.out.print("Key長(zhǎng)度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/補(bǔ)碼方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new Base64().encodeToString(encrypted);//此處使用BASE64做轉(zhuǎn)碼功能彭则,同時(shí)能起到2次加密的作用饮睬。
}
// 解密
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長(zhǎng)度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
public static void main(String[] args) throws Exception {
/*
* 此處使用AES-128-ECB加密模式芒澜,key需要為16位。
*/
String cKey = "1234567812345678";
// 需要加密的字串
String cSrc = "111111111";
System.out.println(cSrc);
// 加密
String enString = AESUtil.Encrypt(cSrc, cKey);
System.out.println("加密后的字串是:" + enString);
// 解密
String DeString = AESUtil.Decrypt(enString, cKey);
System.out.println("解密后的字串是:" + DeString);
}
}