我正在尝试使用aes算法对一些文本进行加密和解密,如:
private static final String ALGORITHM = "AES";
private static final String MODE = "AES/CBC/PKCS7Padding";
public String encrypt(String value, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(MODE);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(key.getBytes()));
byte[] values = cipher.doFinal(value.getBytes());
return Base64.encodeToString(values, Base64.URL_SAFE);
}
public String decrypt(String value, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] values = Base64.decode(value, Base64.DEFAULT);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(MODE);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(key.getBytes()));
return new String(cipher.doFinal(values));
}
加密代码工作得非常好,但当我试图解密加密文本时,它返回一个错误的base64。
我以前尝试过的:
我已经尝试将base64.default更改为base64.url\u safe,但它给了我相同的错误。
此外,我还尝试用“_”和“-”替换“/”和“+”,但它也不起作用。
这是我加密并试图解密的值:
ssg2w+dv7es7/wwaeacoaosvnyksollefbms8tyr+jc=
谢谢你的帮助。。。
1条答案
按热度按时间ohfgkhjo1#
试试这个
org.apache.commons.codec.binary.base64.encodebase64string()org.apache.commons.codec.binary.base64.decodebase64()