AES Negative bytes

前端 未结 2 1494
天命终不由人
天命终不由人 2021-01-07 15:55

The following is an extract from using AES encryption in Java:

  encryptedData =   encryptCipher.doFinal(strToEncrypt.getBytes());

The foll

2条回答
  •  再見小時候
    2021-01-07 16:34

    Java's bytes are signed, C# bytes are unsigned (there's also an sbyte type in C#, that no one uses, which works like Java's bytes).

    It doesn't matter. They are different in some regards, namely

    • when converted to int, C#'s bytes will be zero-extended, Java's bytes will be sign-extended (which is why you almost always see & 0xFF when bytes are used in Java).
    • when converted to string, Java's bytes will have their 128 - 255 range mapped to -128 - -1. Just ignore that.

    The actual value of those bytes (that is, their bit-pattern) is what actually matters, a byte that is 0xAA will be 0xAA regardless of whether you interpret it as 170 (as in C#) or -86 (as in Java). It's the same thing, just a different way to print it as string.


    new MemoryStream((byte)cipherText)) definitely doesn't do the right thing (or anything, it shouldn't even compile). The related new MemoryStream((byte[])cipherText)) wouldn't work either, you can't cast between primitive arrays like that. cipherText should just be a byte[] to begin with.

提交回复
热议问题