Mac sha256 = Mac.getInstance("HmacSHA256");
sha256.init(new SecretKeySpec(key.getBytes("UTF8"), "HmacSHA256"));
byte[] a = sha256.doFinal(value.getBytes("UTF8"));
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
---
private final String cKey = "DyCgD3HGbZWxqAo4";
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長度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"演算法/模式/補碼方式"
IvParameterSpec iv = new IvParameterSpec(cKey.getBytes());//使用CBC模式,需要一個向量iv,可增加加密演算法的強度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return Base64.getEncoder().encodeToString(encrypted);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。
}
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
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("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(cKey.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = Base64.getDecoder().decode(sSrc);//先用base64解密
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;
}
}