public class AESUtil {
// 加密
public static byte[] Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key爲空null");
return null;
}
byte[] raw = new byte[16];
byte[] src = new byte[16];
if (sKey.length() == 16) {
raw = sKey.getBytes("utf-8");
}
if (sKey.length() < 16 && sKey.length() > 0) {
byte[] bytes = sKey.getBytes();
int length = bytes.length;
byte[] data2 = new byte[16 - length];
raw = StringUtils.addBytes(bytes, data2);
}
if (sSrc.length() == 16) {
src = sKey.getBytes("utf-8");
}
if (sSrc.length() < 16 && sSrc.length() > 0) {
byte[] bytes = sSrc.getBytes();
int length = bytes.length;
byte[] data2 = new byte[16 - length];
src = StringUtils.addBytes(bytes, data2); //數組合並,主要是補齊到16位,這裏必須是16位的整數
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");// "算法/模式/補碼方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src);
return encrypted;
}
// 解密
public static String Decrypt(byte[] sSrc, String sKey) throws Exception {
try {
if (sKey == null) {
System.out.print("Key爲空null");
return null;
}
byte[] raw = new byte[16];
if (sKey.length() == 16) {
raw = sKey.getBytes("utf-8");
}
if (sKey.length() < 16 && sKey.length() > 0) {
byte[] bytes = sKey.getBytes();
int length = bytes.length;
byte[] data2 = new byte[16 - length];
raw = StringUtils.addBytes(bytes, data2);
}
// byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
// byte[] encrypted1 = new Base64().decode(sSrc);// 先用base64解密
try {
byte[] original = cipher.doFinal(sSrc);
return new String(original);
} 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 = "cdwzdl.cn";
// 需要加密的字串
String cSrc = "20191029111204";
byte[] bytes = cSrc.getBytes();
System.out.println(cSrc);
// 加密
byte[] enString = AESUtil.Encrypt(cSrc, cKey);
byte[] hexString2Bytes = StringUtils
.HexString2Bytes("2cb12e2aa8b2fe51f4dab67b18ac3b9a"
.toUpperCase());
// 解密
String DeString = AESUtil.Decrypt(enString, cKey);
System.out.println("解密後的字串是:" + DeString);
String DeString111 = AESUtil.Decrypt(hexString2Bytes, cKey);
System.out.println("解密後的字串是1111:" + DeString111);
}