/**
* deEncryption method.
*
* @param data
* @param key
* @param iv
* @return
* @throws Exception
*/
public static String desEncrypt(String data, String key, String iv) throws Exception {
byte[] encrypted = new BASE64Decoder().decodeBuffer(data);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
return originalString;
}
/**
* encryption method.
* @param key 随机生成的aesKey加密因子
* @param initVector
* @param value the data to be encrypted.
* @return
*/
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ new BASE64Encoder().encode(encrypted));
return new BASE64Encoder().encode(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
Android中AES加密和解密
最新推荐文章于 2024-08-19 19:15:48 发布