AES加密工具类和调用示例
程序员文章站
2024-03-14 14:03:58
...
- 工具类代码
public class AESEncryptUtil {
//private static final transient Logger log = LoggerFactory.getLogger(AESEncryptUtil.class);
public AESEncryptUtil() {
}
public static byte[] encrypt(byte[] bytes, String password) {
try {
KeyGenerator e = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes("utf-8"));
e.init(128, secureRandom);
SecretKey secretKey = e.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(1, key, getSpec(cipher, secureRandom));
return cipher.doFinal(bytes);
} catch (Exception var8) {
//log.error(var8.getMessage(), var8);
var8.printStackTrace();
System.out.println("AESEncryptUtil exception:" + var8.getMessage());
return null;
}
}
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator e = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes("utf-8"));
e.init(128, secureRandom);
SecretKey secretKey = e.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(2, key, getSpec(cipher, secureRandom));
return cipher.doFinal(content);
} catch (Exception var8) {
//log.error(var8.getMessage(), var8);
var8.printStackTrace();
System.out.println("AESEncryptUtil exception:" + var8.getMessage());
return null;
}
}
private static AlgorithmParameterSpec getSpec(Cipher cipher, SecureRandom secureRandom) {
byte[] iv = new byte[cipher.getBlockSize()];
secureRandom.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
return ivspec;
}
}
- 调用示例
public static void main(String[] args) throws Exception{
byte[] encrypt = AESEncryptUtil.encrypt("HZT_2020".getBytes(), "123");
String s = DatatypeConverter.printHexBinary(encrypt);
System.out.println(s);
byte[] bytes = DatatypeConverter.parseHexBinary(s);
byte[] decrypt = AESEncryptUtil.decrypt(bytes, "123");
String mm = new String(decrypt,"UTF-8");
System.out.println(mm);
}
- 测试结果
- 参考文章
用到了工具类:javax.xml.bind.DatatypeConverter ,将byte数组转化为16进制字符串输出。之前没用此工具类方法时,解密时报错:
Input length must be multiple of 16 when decrypting with padded cipher。
参考文章地址,点此进入
上一篇: AES 对称加解密 Java代码实现
下一篇: PHP学习——面向对象