jeudi 6 mai 2021

How to implement a os.urandom function - Python2

I'm implementing a function in order to replace os.urandom(n). The code below is what I have so far:

def random_entropy(n):
    """
    Returns a random entropy, which is a sequence of numbers between 0, 255

    :n: a integer number
    """
    if n <= 0:
        return ""
    buffer = []
    for i in range(0, n):
        number = random.randint(0, 255)
        buffer.append(hex(number))
    
    return ''.join(buffer)

if I go to the terminal, I get the following output:

>>> import os
>>> os.urandom(10)
'm\xd4\x94\x00x7\xbe\x04\xa2R'
>>> type(os.urandom(10))
<type 'str'>
>>> map(ord, os.urandom(10))
[65, 120, 218, 135, 66, 134, 141, 140, 178, 25]

in the end, I want my function to return a similar output as os.urandom: 'm\xd4\x94\x00x7\xbe\x04\xa2R' (I mean, the binary output). How can I achieve that? I'm implementing this for an ecdsa module for SGX, so I can't use the os or secrets packages.

From the Python documentation:

Return a string of size random bytes suitable for cryptographic use.




Aucun commentaire:

Enregistrer un commentaire