package com.company;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES256Util {
private static final byte[] RAW = {50, -115, -81, -50, -32, 55, -120, 112, 4, -98, -78, -8, 5, 56, -46, -19};
// 加密
public static String encrypt(String s) throws Exception {
byte[] raw = Arrays.copyOf(RAW, 16);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(raw);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(s.getBytes("UTF-8"));
return URLEncoder.encode(new String(encrypted,"ISO-8859-1"), "ISO-8859-1");
}
// 解密
public static String decrypt(String s) throws Exception {
byte[] raw = Arrays.copyOf(RAW, 16);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(raw);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted = URLDecoder.decode(s, "ISO-8859-1").getBytes("ISO-8859-1");
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original, "UTF-8");
return originalString;
}
public static void main(String args[]) throws Exception {
String msg = AES256Util.encrypt("我只是个测试!");
System.out.println(msg);
System.out.println(AES256Util.decrypt(msg));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…