public class AesUtils {
/**
* 加密方式
*/
private static final String INSTANCE = "AES/ECB/PKCS5Padding";
/**
* 生成key
*/
public static String generateKey() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();
byte[] byteKey = secretKey.getEncoded();
return Hex.encodeHexString(byteKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* AES加密
*
* @param key 生成的key
* @param data 需要加密的数据
* @return 密文
*/
public static String encode(String key, String data) {
try {
Key thatKey = new SecretKeySpec(Hex.decodeHex(key), "AES");
Cipher cipher = Cipher.getInstance(INSTANCE);
cipher.init(Cipher.ENCRYPT_MODE, thatKey);
byte[] result = cipher.doFinal(data.getBytes());
return Hex.encodeHexString(result);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* AES解密
*
* @param key 生成的key
* @param data 密文
* @return 明文
*/
public static String decode(String key, String data) {
try {
Key thatKey = new SecretKeySpec(Hex.decodeHex(key), "AES");
Cipher cipher = Cipher.getInstance(INSTANCE);
cipher.init(Cipher.DECRYPT_MODE, thatKey);
byte[] result = cipher.doFinal(Hex.decodeHex(data));
return new String(result);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
Aes加密工具类
最新推荐文章于 2024-06-21 17:05:23 发布