【发布时间】:2019-05-29 13:22:39
【问题描述】:
我有一个用于加密文本的系统,但我试图创建一个用于解密文本的系统,但它不起作用。系统是:
将加密文本初始化为字节[]
用加密文本初始化解密文本
他只返回加密的文本,而不是解密的文本。你有调试这个的想法吗?
提前致谢。
byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
String key = "Bép12345Taruy'(";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
return encrypted;
}
String getDecrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
String key = "Bép12345Taruy'(";
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
return decrypted;
}
【问题讨论】:
-
也分享你使用这些功能的代码。
-
有一点是错误的:您的
getEncrypt方法返回一个字符串,但加密的文本由不能存储在字符串中的字节组成。不要这样做new String(encrypted)。使方法返回byte[]而不是String。字符串不是任意字节的合适容器。 -
可能是 byte[] 到 Base64 字符串。如果我错了,我认为这是正确的做法。
标签: java security encryption