C# Unsigned bytes Encryption to Java Signed bytes Decryption

女生的网名这么多〃 提交于 2019-12-02 02:35:01

Although you cannot use unsigned bytes in Java, you may simply ignore the issue.

AES - and all modern symmetric ciphers - operates on bytes, and the input and output have been defined to be bytes (or octets). Input and output have been standardized by NIST and test vectors are available.

If you look at the separate bit content of the bytes then {200,201,202} in C# and {(byte)200, (byte)201, (byte)202} in Java are identical. This is because Java uses two-complement representation of bytes.

Take the number 200 as integer: this will be 11010000 in binary, representing the number -56 in Java if used in a (signed) byte in two complements. Now symmetric ciphers will simply transform these bits to another (normally using a full block of bits).

Once you have retrieved the answer you will see that they are identical both in C# and Java when you look at the separate bits. C# will however interpret those as unsigned values and Java as signed values.

If you want to print out or use these values as signed numbers in Java then you have to convert them to positive signed integers. The way to do this is to use int p = b & 0xFF.

This does the following (I'll use the number 200 again):

  1. The (negative) byte value is expanded to a signed integer, remembering the sign bit:

    11010000 becomes 11111111 11111111 11111111 11010000

  2. This value is "masked" with 0xFF or 00000000 00000000 00000000 11111111 by performing the binary AND operator:

    11111111 11111111 11111111 11010000 & 00000000 00000000 00000000 11111111 = 00000000 00000000 00000000 11010000

This value is identical to the value 200 as a signed integer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!