【问题标题】:Encrypting and Decrypting Text in Java [duplicate]在 Java 中加密和解密文本 [重复]
【发布时间】: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,感谢您链接解决方案!

标签: java string encryption


【解决方案1】:

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

【讨论】:

  • 您的getBytesnew String 使用默认字符编码,它可能因系统、用户和时间而异。使用字符编码时,几乎总是需要一个固定的编码。 UTF-8 通常是一个不错的选择,尤其是在字符集为 Unicode 的情况下,如 Java String
猜你喜欢
  • 2016-07-07
  • 1970-01-01
  • 2012-05-06
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
相关资源
最近更新 更多