I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?
Update: forgot to mention that the numbers I'm dealing with are 768 bit unsigned integers.
An int value can be converted into bytes by using the method int. to_bytes().
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
Number Type Conversion Type int(x) to convert x to a plain integer. Type long(x) to convert x to a long integer. Type float(x) to convert x to a floating-point number. Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
With Python 3.2 and later, you can use int.to_bytes
and int.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
Everyone has overcomplicated this answer:
some_int = <256 bit integer> some_bytes = some_int.to_bytes(32, sys.byteorder) my_bytearray = bytearray(some_bytes)
You just need to know the number of bytes that you are trying to convert. In my use cases, normally I only use this large of numbers for crypto, and at that point I have to worry about modulus and what-not, so I don't think this is a big problem to be required to know the max number of bytes to return.
Since you are doing it as 768-bit math, then instead of 32 as the argument it would be 96.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With