java - 在 Java 中加密和解密文本

标签 java string encryption

<分区>


我正在尝试加密和解密我从用户那里得到的字符串。
我在谷歌上做了一些搜索,我找到了这段代码。

   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();
            }

关于java - 在 Java 中加密和解密文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49401879/

相关文章:

java - 匹配两个字符串列表,其中一个列表可以包含带有通配符 '?' 的字符串

java - 如何使用 swagger-codegen-plugin (maven) 生成客户端代码?

java - 如何避免 Java 中不必要的类引用?

c# - 如何使用 fo-dicom 获取 dicom 项目的完整字符串元素?

c++ - 字符串的字典序比较[不区分大小写]

ios - 避免我的 iOS 应用程序中的文件易于替换

javascript - openpgpjs 示例中的错误 : 'openpgp.encrypt is not a function'

matlab - 加密 matlab 结构体的部分

java - 如何进行输入处理

java - 无法从 Servlet 打印 JSP 中的 ArrayList