Forcing integer overflow in Python

Viewed 1250

I am trying to emulate something written in Java in python. There is a symmetric encryption algorithm in the Java part, where key generation relies on Java long integers overflowing. I now need to do this in Python to be able to decrypt there. I did not write the encryption algorithm, and I cannot change that. This is part of the key generator function in Java:

long a;
long b;
...
for (...)
    ...
    a = b + ((b << 1) + (b << 4) + (b << 7) + (b << 8) + (b << 35));

Now when I copy this as it is to Python, I will receive massive numbers, as Python does what it is supposed to do and adds more bytes to my integer, while in Java the integers just keep overflowing and eventually a 64 bit key is returned. This is not the entirety of the code, it is actually a loop that keeps doing this and other things to a and b, so I cannot just take the highest 64 bits or something like that and treat that as my new a.

However, I now need to emulate this behaviour in Python to get my decryption key.

How do I do this in Python? Is it even possible, or do I need to rely on a C function for this part, and do the key generation there?

2 Answers

If you store all of the integers in numpy arrays they will overflow (because numpy is using C for arithmetic).

There is no need to use numpy or any other external library; raw Python is powerful enough for what you're after. Although if you can express your whole algorithm in terms of vector operations, a numpy implementation will be much faster.

Just add this line after the one you showed, which gives the remainder of a modulo 2 to the power 64:

a = a % 2**64

Or you can use this line, which does bitwise AND with a number whose final 64 bits are 1s:

a = a & ((1 << 64) - 1)

These two statements are equivalent, and the performance difference is probably negligible. So I suggest choosing the one that makes most sense to you, which will depend on whether you consider it to be more of an arithmetic operation (the first one) or a bitwise operation. Obviously change 64 to 32 or whatever else is appropriate.

Related