开发者

Why does my encrypted string looks like consisting of only question marks?

开发者 https://www.devze.com 2022-12-20 17:47 出处:网络
I\'m encrypting a string in Java, and when I\'m printing the encrypted data, I see only question marks.

I'm encrypting a string in Java, and when I'm printing the encrypted data, I see only question marks.

As an example:

  • Plain text: jjkkjlkljkj

  • Encrypted text: ???????????

  • After decrypting this text again, I'm getting jjkkjlkljkj again.

So it looks like the encryption worked right. But 开发者_如何学运维why can I see only question marks?


Yes, it's because you can't print the strings that are resulting from the encryption.

Note that saving the encrypted result in a string will possibly result in loss of the data, so don't do that. Take it as a byte array, and convert it to a displayable format, like Base64 or just simple Hex.


The root cause of the problem is the way how you presented the encrypted data. The character encoding used doesn't recognize those characters as one of its charset, nor does it have a suitable glyph (font) for those characters. Even then, when you used the "correct" character encoding (try to display it with UTF-8) it would not have been human readable.

I suppose that you have it in flavor of a byte[] and are trying to convert it to String using new String(bytearray). If your purpose is to transfer it as a String instead of a byte[], then you should rather use either Apache Commons Codec Base64#encodeBase64String() or to convert the byte[] to a hexstring like follows:

StringBuilder hex = new StringBuilder(bytea.length * 2);
for (byte b : bytea) {
    if ((b & 0xff) < 0x10) hex.append("0");
    hex.append(Integer.toHexString(b & 0xff));
}
String hexString = hex.toString();
0

精彩评论

暂无评论...
验证码 换一张
取 消