AES在项目中的使用
Java AES 加解密。
/*
* 加密方法
*/
public static String encrypt(String message){
byte[] unencrypted = message.getBytes(Charset.forName("utf-8"));
byte[] aesKey = "0123456789123456".getBytes();
// 设置加密模式为AES的CBC模式
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
try {
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
// 加密
byte[] encrypted = null;
try {
encrypted = cipher.doFinal(unencrypted);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
// 使用BASE64对加密后的字符串进行编码
String base64Encrypted = new Base64().encodeToString(encrypted);
System.out.println(base64Encrypted);
return base64Encrypted;
}
/*
* 解密方法
*/
public static String decode(String text){
byte[] aesKey = "0123456789123456".getBytes();
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
try {
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text);
// 解密
byte[] original = null;
try {
original = cipher.doFinal(encrypted);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
String str = new String(original);
return str;
}