Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python long/int to fixed size byte array

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.

like image 945
cdecker Avatar asked Jan 04 '12 17:01

cdecker


People also ask

How do you convert int to byte in Python?

An int value can be converted into bytes by using the method int. to_bytes().

How do you convert int to byte value?

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).

How do you convert long to int in Python?

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.


2 Answers

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

like image 118
Jack O'Connor Avatar answered Sep 29 '22 11:09

Jack O'Connor


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.

like image 34
sparticvs Avatar answered Sep 29 '22 11:09

sparticvs