【问题标题】:Java byte[] to String and UTF-8Java byte[] 到 String 和 UTF-8
【发布时间】:2011-12-02 22:49:07
【问题描述】:

我正在为学校作业实施Cipher Block Chaining,问题要求采用String 并返回另一个String 的方法。起初,我认为这很奇怪,byte[] 变量会更合适,但仍然实现了一个方法。基本上,这是代码:

static public String encode(String message) {
   byte[] dataMessage = message.getBytes();
   ByteArrayOutputStream out = new ByteArrayOutputStream();

   byte last = (byte) (Math.random() * 256);
   byte cur;
   out.write(last);

   for (byte b : data) {
      cur = (byte) (b^last);
      System.out.println("Encode '" + (char) b + "' = " + b + "^" + last + " > " + cur );
      out.write( cur );
      last = cur;
   }

   System.out.println("**ENCODED BYTES = " + Arrays.toString(out.toByteArray()));
   System.out.println("**ENCODED STR   = " + Arrays.toString(out.toString().getBytes()));

   return out.toString();
}

decode 方法的工作原理类似。有时,该方法会吐出类似的结果

Encode 'H' = 72^109 > 37
Encode 'e' = 101^37 > 64
Encode 'l' = 108^64 > 44
Encode 'l' = 108^44 > 64
Encode 'o' = 111^64 > 47
**ENCODED BYTES = [109, 37, 64, 44, 64, 47]
**ENCODED STR   = [109, 37, 64, 44, 64, 47]

但有时也会吐诸如此类的东西

Encode 'H' = 72^-63 > -119
Encode 'e' = 101^-119 > -20
Encode 'l' = 108^-20 > -128
Encode 'l' = 108^-128 > -20
Encode 'o' = 111^-20 > -125
**ENCODED BYTES = [-63, -119, -20, -128, -20, -125]
**ENCODED STR   = [-17, -65, -67, -17, -65, -67, -17, -65, -67, -17, -65, -67]

我认为这与 UTF-8(系统的默认编码)有关,但我不太熟悉 究竟为什么会返回给定的字符串字节。

【问题讨论】:

    标签: java string utf-8 encryption


    【解决方案1】:

    您不能采用任意字节序列并假定它是有效的 UTF-8 编码字符串。因此,我怀疑toString 方法,如documented将格式错误的输入和不可映射的字符序列替换为平台默认字符集的默认替换字符串

    因此,您不应该像这样将纯二进制数据转换为字符串。使用 Hex 或 Base64 等编码将字节转换为可打印的字符串,反之亦然。

    Apache commons-codec 有一个 Base64 实用程序类。

    【讨论】:

    • 是的,它替换了每个字符序列(其中四个,UTF-8 有一个自同步属性,可以跳到看起来像下一个多字节字符的开头)被替换为 U +FFFD 替换字符(在 UTF8 中:0xef 0xbf 0xbd)。
    • 是的,这就是我认为发生的事情(关于替换字符)。然后我将使用 Base64 实现。
    【解决方案2】:

    这个:

    out.toString().getBytes()
    

    没有按照您的预期进行。它采用加密的字节并将这些字节解释为好像它们是 UTF-8 编码的字符串。然后它将该字符串中的字符转换回字节。

    您不能只取任意字节(在本例中为加密数据),然后将其视为 UTF-8 编码文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2013-02-15
      • 2014-10-16
      • 1970-01-01
      • 2012-10-08
      • 2013-09-11
      • 2022-09-26
      相关资源
      最近更新 更多