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

前端 未结 2 938
猫巷女王i
猫巷女王i 2020-12-12 01:41

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

相关标签:
2条回答
  • 2020-12-12 02:13

    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 讨论(0)
  • 2020-12-12 02:32

    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.

    0 讨论(0)
提交回复
热议问题