AES Negative bytes

前端 未结 2 1495
天命终不由人
天命终不由人 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.

    0 讨论(0)
  • 2021-01-07 16:34

    You could turn it into a string with some encoding, like:

    encryptedData =   encryptCipher.doFinal(strToEncrypt.getBytes());
    String s = new String(encryptedData, "Base-64");
    

    Using the same standardized encoding, both C# and Java should be able to reconstruct each others encrypted data from that string.

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