【发布时间】:2018-08-30 07:26:31
【问题描述】:
我正在尝试加密和解密从用户那里获得的字符串。
我在谷歌上做了一些搜索,我找到了这段代码。
try{
String text="";
String key="Bar12345Bar12345";
System.out.print("Input Text>>");
text=sc.nextLine();
Key aesKey = new SecretKeySpec(key.getBytes(),"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
String encryptedValue = Base64.getEncoder().encodeToString(encrypted);
System.out.println(encryptedValue);
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.out.println(decrypted);
}catch(Exception e){
e.printStackTrace();
}
但是给出的字符串是乱码(某种符号),它返回了一个错误。
有没有其他方法来加密和解密文本?或者可能需要进行一些更改才能使代码正常工作?
提前致谢!
这里是参考链接,以备不时之需
http://www.software-architect.net/articles/using-strong-encryption-in-java/introduction.html
编辑: 感谢@sgrillon 指出解决方案的链接。
【问题讨论】:
-
在 BAse64 中对 byte[] 进行加密编码后,不会报错。另外,在解密之前,先解码Base 64,然后再解密字符串
-
@AshishMathew 哦,是的,事实证明您需要先将其编码回 Base64,感谢您链接解决方案!
-
查看@Greg 对stackoverflow.com/questions/10759392/…的回复
标签: java string encryption