用Java加密和解密文本
用Java加密和解密文本,java,string,encryption,Java,String,Encryption,我正在尝试加密和解密从用户处获得的字符串。 我在谷歌上搜索了一下,找到了这段代码。 try{ String text=""; String key="Bar12345Bar12345"; System.out.print("Input Text>>"); text=sc.nextLine(); Key aesKey = new SecretKeySpec(key.getBytes(),"AES")
我正在尝试加密和解密从用户处获得的字符串。
我在谷歌上搜索了一下,找到了这段代码。
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();
}
但是给出的字符串是乱码(某种符号),返回了一个错误。有没有其他加密和解密文本的方法?或者可能需要对代码进行一些更改才能正常工作?
提前谢谢 这里是参考链接,以备您需要
编辑:
感谢@sgrillon指出解决方案的链接。因为
System.out.println(新字符串(加密))代码>将字节数组转换为不可读的非ASCII格式。要使其可读,需要使用Base64编码器将此字节[]转换为ASCII格式
我已将您的代码输出转换为Base64格式输出,以便您能够读取输出
Scanner sc = new Scanner(System.in);
try{
String text="";
String key="Bar12345Bar12345";
System.out.print("Input Text>> ");
text= sc.nextLine();
java.security.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 outputString = Base64.getEncoder().encodeToString(encrypted);
System.out.println(outputString);
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(Base64.getDecoder().decode(outputString.getBytes())));
System.out.println(decrypted);
}catch(Exception e){
e.printStackTrace();
}
在对BAse64中的字节[]进行加密编码后,它不会给出错误。同样,在解密之前,先解码基64,然后解密string@AshishMathew哦,是的,你需要先把它编码回Base64,谢谢你链接这个解决方案!请参阅getBytes
上的@Greg response和new String
使用默认字符编码,这可能因系统、用户和时间而异。当使用字符编码时,几乎总是需要一个固定的编码。UTF-8通常是一个很好的选择,特别是在字符集为Unicode的情况下,就像JavaString
一样。