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¬∙:╪⌡¶
。为什么?如何以正确的字符串格式打印
# 1 楼答案
大多数加密算法(包括blowfish)都处理二进制数据,这意味着它将接收二进制数据,并分离由算法转换的二进制数据(使用提供的规范)
二进制数据,如你所知!=但是,二进制数据可以表示为字符串数据(使用十六进制、base64等)
如果我们看一下您的示例代码,我们可以看到这一行:
这是它一步一步地做的:
它首先使用平台的默认字符集(不推荐,但与此无关)将字符串数据转换为等价的二进制数据
它将二进制数据(以字节数组的形式)传递给doFinal()方法
doFinal()方法通过此行之前的语句(Blowfish、encryption)中指定的规范处理这个字节数组
doFinal()语句返回一个字节数组,该数组表示已处理(在您的例子中是加密)的数据
由于加密操作的性质,数据最初来自字符串这一事实不再相关,这并不能说明数据的来源或类型。加密字节数组现在包含的数据可能不是有效的字符集编码字符串。尝试使用字符集解码字符串很可能会导致垃圾输出,因为二进制数据不再是有效字符串
然而,二进制数据可以通过输出实际字节的值来直接表示,而不是通过字符集等效映射来表示(例如,一个字节的值可能为97,用十六进制表示为:0x61,但通过ASCII解码得到字符“A”)
考虑此代码以输出十六进制:
中的加密数据。注意:不要在没有任何参数的情况下使用getBytes()!提供自己的字符集,如UTF-8。按以下步骤进行:
# 2 楼答案
可以从common-codec使用Base64编码
输出:
# 3 楼答案
用Base64编码(How do I convert a byte array to Base64 in Java?)对字节进行编码
或十六进制:How to convert a byte array to a hex string in Java?
系统。出来println(十六进制编码十六进制字符串(字节))
# 4 楼答案
你可以试试: