This question already has answers here:
Encrypt and decrypt with AES and Base64 encoding
                                
                                    (6个答案)
                                
                        
                                去年关闭。
            
                    

我正在尝试加密和解密从用户那里获得的String。
我在Google上做了一些搜索,发现了这段代码。

   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指出了解决方案的链接。

最佳答案

因为System.out.println(new String(encrypted));将字节数组转换为不可读的非ASCII格式。要使其可读,需要使用Base64编码器将此byte []转换为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();
            }

07-24 18:41