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.
I haven't done any benchmarks, but this recipe "works for me".
The short version: use
'%x' % val
, thenunhexlify
the result. The devil is in the details, though, asunhexlify
requires an even number of hex digits, which%x
doesn't guarantee. See the docstring, and the liberal inline comments for details....and my nosetest unit tests ;-)
Python 2.7 does not implement the int.to- very slow_bytes() method.
I tried 3 methods:
All these methods are very inefficient for two reasons:
Little-endian, reverse the result or the range if you want Big-endian.
Everyone has overcomplicated this answer:
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.