Java byte (byte) array and byte type negative value problem in Python3

In Java, byte arrays can store negative values, because the value range of the byte type in Java is between -128 and 127, while in Python3, the value range of bytes is 0 to 256.

Java-127~128

Python0~256

In some scenarios, such as AES encryption, the definition of parameter values ​​​​such as Key and IV (offset) will be used. In Java, it may be as follows:

public static byte[] iv = new byte[] {
    
     1, 3, 8, 22, -13, 125, -40, -124, -27, -10, 57, 13, 46, 22, -3, 5 };

At this time, if you need to implement the same encryption algorithm through Python3, there will be a problem, that is, the negative value in the above Java code cannot be directly expressed in Python3.

Faced with this situation, the following methods can be used for conversion in Python3:

iv = [1, 3, 8, 22, -13, 125, -40, -124, -27, -10, 57, 13, 46, 22, -3, 5]
iv_byte = bytes(i % 256 for i in iv)

After passing in the corresponding AES algorithm function in Python, the corresponding encryption results are consistent.

Guess you like

Origin blog.csdn.net/wo541075754/article/details/130047477