dongyou8087
2016-01-05 02:48 阅读 21
已采纳

Java Byte to String给出了奇怪的结果?

I have this code:

 private static c e;
  private static byte[] f = { 55, -86, -102, 55, -23, 26, -83, 103, 125, -57, -110, -34, 70, 102, 48, -103 };
  private String a;
  private SecureRandom b;
  private int c;
  private byte[] d;

  public c(String paramString, SecureRandom paramSecureRandom)
  {
    this.a = paramString;
    this.b = paramSecureRandom;
  }

  public static c a()
  {
    if (e == null)
    {
      e = new c("AES/CBC/PKCS7Padding", new SecureRandom());
      e.a(f, 16);
    }
    return e;
  }

With f being the array of bytes and 16 to do with reading 16 bytes of the IV generated with SecureRandom(). (atleast I assume that's what it is doing?) However when I use this:

byte[] byteArray = { 55, -86, -102, 55, -23, 26, -83, 103, 125, -57, -110, -34, 70, 102, 48, -103 };

String value = new String(byteArray, "ISO-8859-1");
    System.out.println(value);

I get this output: 7ª7é­g}ÇÞFf0

I'm attempting to work out how this app i've got generates the encryptionkey used for encrypting/decrypting... that result above surely can't be anything right? Am I completely on the wrong track here?

I've included the full class code here incase it helps: http://pastie.org/private/5fhp9yqknzoansd1vc0xfg

Would really love to know what the code above is actually doing so I can port it to PHP, not too good @ Java.

Thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doucong3048 doucong3048 2016-01-05 03:09

    Your output 7ª7é­g}ÇÞFf0 makes sense to me.

    You are using the character set: ISO-8859-1, and thus the bytes will be decoded to the characters they are mapped to in that character set.

    Your byte array is created using base 10, and java bytes are signed. This means your byte array has the following hexadecimal values (in order):

    37, AA, 9A, 37, E9, 1A, AD, 67, 7D, C7, 92, DE, 46, 66, 30, 99
    

    According to the ISO-8859-1 character set, these values map to the following:

    7, ª, (nil), 7, é, (nil), SHY, g, }, Ç, (nil), Þ, F, f, 0, (nil)
    

    Which is pretty close to what your string is actually. The (nil) characters are not rendered in your string because the character set does not have glyphs for the corresponding values. And for the character SHY, I will assume again there is no glyph (while the standard indicates there actually should be).

    Your output seems correct to me! :)

    Remember, your encryption key is just a sequence of bytes. You shouldn't expect the data to be human-readable.

    点赞 评论 复制链接分享

相关推荐