Although the Python Random module is very practical, for encryption purposes the recommendation is to use the call os.urandom()
, that has randomness most guaranteed by the operating system.
On the other hand it is even more convenient, because the os.urandom
already accepts a parameter with the number of random bytes and returns an object of type bytes - in this case, for 4096 bits, you use os.urandom(512)
- in general for any use you are going to make the bytes object will be more practical than an integer with 4096 bits.
However, the language supports whole numbers of this size - so if you want the numeric value you can do: int.from_bytes(os.urandom(512), "big")
. If you prefer as a text string with 2 hexadecimal digits per byte, you can do os.urandom(512).hex()
(convertible back to bytes with bytes.fromhex(minha_string)
).
Now, let’s assume that you have another function of your choice that generates 32-bit random numbers of fixed size (for example, a call to a driver from a randomized number generator harware device) - in this case, you can use the "struct" module of Python to join 16 calls to its function in a continuous byte object with 512 bytes (and there you can transform into integer, or a hexadecimal string, as above):
struct.pack("=16I", *(random.randrange(0, 2**32) for _ in range(16)))
(In this case I used Random.randrange as an example, but the recommendation is to actually use.urandom, as I explained above). Understanding this expression:
is a call to the function struct.pack
where the first parameter describes the next ones: plus 16 32-bit integers that will be interpreted using the endiannes machine native - little endian in x86_64 - indicated by the "=" sign. Next a Generator Expression that is deployed by the operator *
- each generated element is passed to the function as a positional parameter. The expression in turn simply repeats 16 times, given in for _ in range(16)
the call the desired function.
Right. But I need to create through some algorithms for the purpose of studying them. For example, I will use 3 algorithms: Park-Miller, Xorshfit, Linear Congruential Generator. Using these 3 algorithms I have to be able to generate a very large number.
– Daniel Boso