您的位置:首页 > 其它

AES在项目中的使用

2015-12-18 16:03 232 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/xiaoxiang8385/article/details/50352397

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: