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.
long/int to the byte array looks like exact purpose of
struct.pack
. For long integers that exceed 4(8) bytes, you can come up with something like the next:Basically what you need to do is convert the int/long into its base 256 representation -- i.e. a number whose "digits" range from 0-255. Here's a fairly efficient way to do something like that:
You many not need the
reversed()
call depending on the endian-ness desired (doing so would require the padding to be done differently as well). Also note that as written it doesn't handle negative numbers.You might also want to take a look at the similar but highly optimized
long_to_bytes()
function in thenumber.py
module which is part of the open source Python Cryptography Toolkit. It actually converts the number into a string, not a byte array, but that's a minor issue.With Python 3.2 and later, you can use
int.to_bytes
andint.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytesOne-liner:
The 192 is 768 / 4, because OP wanted 768-bit numbers and there are 4 bits in a hex digit. If you need a bigger
bytearray
use a format string with a higher number. Example:[My answer had used
hex()
before. I corrected it withformat()
in order to handle ints with odd-sized byte expressions. This fixes previous complaints aboutValueError
.]You can try using struct: