使用原始的方法
public static String EncryptEncode(String content, String... key) throws Exception {
String encryptKey = "audaque2018";
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encryptKey.getBytes());
keyGenerator.init(128, random);
SecretKey originalKey = keyGenerator.generateKey();
byte[] rawByte = originalKey.getEncoded();
SecretKey secretKey = new SecretKeySpec(rawByte, "AES");
Cipher cipher = Cipher.getInstance("AES"); // AES/ECB/PKCS5Padding
cipher.init(1, secretKey);
byte[] byteEncode = content.getBytes("utf-8");
byte[] bytesAes = cipher.doFinal(byteEncode);
return new String((new BASE64Encoder()).encode(bytesAes));
}
public static String DecryptDecode(String content, String... key) throws Exception {
String encryptKey = "audaque2018";
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encryptKey.getBytes());
keyGenerator.init(128, random);
SecretKey originalKey = keyGenerator.generateKey();
byte[] byteArray = originalKey.getEncoded();
SecretKey secretKey = new SecretKeySpec(byteArray, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(2, secretKey);
byte[] byteContent = (new BASE64Decoder()).decodeBuffer(content);
byte[] byteEncode = cipher.doFinal(byteContent);
return new String(byteEncode, "utf-8");
}
使用 hutools
public static String invokeEncryptEncode(String content, String... key) throws NoSuchAlgorithmException {
String encryptKey = "audaque2018";
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encryptKey.getBytes());
byte[] keyBytes = new byte[16];
random.nextBytes(keyBytes);
AES aes = SecureUtil.aes(keyBytes);
byte[] encryptedBytes = aes.encrypt(content.getBytes());
String resultEncode = Base64Encoder.encode(encryptedBytes);
return resultEncode;
}
public static String invokeDecryptDecode(String encryptedContent, String... key) throws NoSuchAlgorithmException {
String encryptKey = "audaque2018";
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(encryptKey.getBytes());
byte[] keyBytes = new byte[16];
random.nextBytes(keyBytes);
AES aes = SecureUtil.aes(keyBytes);
byte[] encryptedBytes = Base64Decoder.decode(encryptedContent);
byte[] decryptedBytes = aes.decrypt(encryptedBytes);
return new String(decryptedBytes);
}
标签:AES,sha1,JAVA,String,random,ASE,new,byte,SecureRandom
From: https://www.cnblogs.com/guanchaoguo/p/17611999.html