有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我没有得到字符串格式的输出?

在下面的代码片段中,我尝试以简单的字符串格式打印encrypted array

        KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("Blowfish"); 
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        String input = "password";
        byte encrypted[] = cipher.doFinal(input.getBytes());
        String s = new String(encrypted);
        System.out.println(s);

但我得到的是`┐╫Y²▓ô┴Vh¬∙:╪⌡¶。为什么?如何以正确的字符串格式打印


共 (4) 个答案

  1. # 1 楼答案

    大多数加密算法(包括blowfish)都处理二进制数据,这意味着它将接收二进制数据,并分离由算法转换的二进制数据(使用提供的规范)

    二进制数据,如你所知!=但是,二进制数据可以表示为字符串数据(使用十六进制、base64等)

    如果我们看一下您的示例代码,我们可以看到这一行:

    byte encrypted[] = cipher.doFinal(input.getBytes());
    

    这是它一步一步地做的:

    1. 它首先使用平台的默认字符集(不推荐,但与此无关)将字符串数据转换为等价的二进制数据

    2. 它将二进制数据(以字节数组的形式)传递给doFinal()方法

    3. doFinal()方法通过此行之前的语句(Blowfish、encryption)中指定的规范处理这个字节数组

    4. doFinal()语句返回一个字节数组,该数组表示已处理(在您的例子中是加密)的数据

    由于加密操作的性质,数据最初来自字符串这一事实不再相关,这并不能说明数据的来源或类型。加密字节数组现在包含的数据可能不是有效的字符集编码字符串。尝试使用字符集解码字符串很可能会导致垃圾输出,因为二进制数据不再是有效字符串

    然而,二进制数据可以通过输出实际字节的值来直接表示,而不是通过字符集等效映射来表示(例如,一个字节的值可能为97,用十六进制表示为:0x61,但通过ASCII解码得到字符“A”)

    考虑此代码以输出十六进制:

    中的加密数据。
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    SecretKey secretKey = keyGenerator.generateKey();
    Cipher cipher = Cipher.getInstance("Blowfish"); 
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    String input = "password";
    byte encrypted[] = cipher.doFinal(input.getBytes());
    
    StringBuilder str = new StringBuilder();
    
    for(byte b:encrypted){
         str.append(String.format("%02x", b));
    }
    
    String encData = str.toString();
    System.out.println(encData);
    

    注意:不要在没有任何参数的情况下使用getBytes()!提供自己的字符集,如UTF-8。按以下步骤进行:

    byte encrypted[] = cipher.doFinal(input.getBytes(Charset.forName("UTF-8")));
    
  2. # 2 楼答案

    可以从common-codec使用Base64编码

        KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        String input = "password";
        byte encrypted[] = cipher.doFinal(input.getBytes());
        System.out.println(new String(Base64.encodeBase64(encrypted)));
    

    输出:

    8KA8ahr6INnY4qqtzjAJ8Q==
    
  3. # 4 楼答案

    你可以试试:

    new String(bytes, StandardCharsets.UTF_8)