Пример #1
0
def _open_urandom():
    if _urandom is None:
        raise error("os.urandom function not found")
    
    # Check that we can read from os.urandom()
    try:
        x = _urandom(20)
        y = _urandom(20)
    except Exception, exc:
        raise error("os.urandom failed: %s" % str(exc), exc)
Пример #2
0
 def getrandbits(self, k):
     """getrandbits(k) -> x.  Generates an int with k random bits."""
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     numbytes = (k + 7) // 8                       # bits / 8 and rounded up
     x = int.from_bytes(_urandom(numbytes), 'big')
     return x >> (numbytes * 8 - k)                # trim excess bits
Пример #3
0
    def seed(self, a=None, version=2):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        For version 2 (the default), all of the bits are used if *a *is a str,
        bytes, or bytearray.  For version 1, the hash() of *a* is used instead.

        If *a* is an int, all bits are used.

        """

        if a is None:
            try:
                a = int.from_bytes(_urandom(32), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256) # use fractional seconds

        if version == 2:
            if isinstance(a, (str, bytes, bytearray)):
                if isinstance(a, str):
                    a = a.encode()
                a += _sha512(a).digest()
                a = int.from_bytes(a, 'big')

        super().seed(a)
        self.gauss_next = None
Пример #4
0
    def seed(self, a=None):

        """Initialize internal state from hashable object.


        None or no argument seeds from current time or from an operating

        system specific randomness source if available.


        If a is not None or an int or long, hash(a) is used instead.

        """


        if a is None:

            try:

                # Seed with enough bytes to span the 19937 bit

                # state space for the Mersenne Twister

                a = long(_hexlify(_urandom(2500)), 16)

            except NotImplementedError:

                import time

                a = long(time.time() * 256) # use fractional seconds


        super(Random, self).seed(a)

        self.gauss_next = None
Пример #5
0
    def seed(self, a=None):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or an int or long, hash(a) is used instead.

        If a is an int or long, a is used directly.  Distinct values between
        0 and 27814431486575L inclusive are guaranteed to yield distinct
        internal states (this guarantee is specific to the default
        Wichmann-Hill generator).
        """

        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

        if not isinstance(a, (int, long)):
            a = hash(a)

        a, x = divmod(a, 30268)
        a, y = divmod(a, 30306)
        a, z = divmod(a, 30322)
        self._seed = int(x)+1, int(y)+1, int(z)+1

        self.gauss_next = None
Пример #6
0
 def getrandbits(self, k):
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     if k != int(k):
         raise TypeError('number of bits should be an integer')
     numbytes = (k + 7)//8
     x = int.from_bytes(_urandom(numbytes), 'big')
     return x >> numbytes*8 - k
Пример #7
0
def handle_auth_serv(my_conn,password):
    """handle authentication for the server side of the virtual connection

    handle_auth_serv(my_conn,password)
    
    my_conn  :: socket :: connected socket that is recieving the authentication attempt
    password :: str    :: password used for authentication

    returns -> bool
    
    throws  TOSDB_VirtualizationError 
    """

    my_sock, my_addr = my_conn

    #hash/overwite password
    password = _hash_password(password)

    # generate random sequence and iv
    rseq = _urandom(RAND_SEQ_SZ)    
    iv = _urandom(_AES.block_size)
    
    # send to client 
    _send_tcp(my_sock, iv+rseq)    

    # get back the encrypted version
    try:
        crypt_seq_cli = _recv_tcp(my_sock) #raw (no need to unpack)
    except ConnectionAbortedError as e:
        raise TOSDB_VirtualizationError("client aborted connection", e)
    except _socket.timeout:
        raise TOSDB_VirtualizationError("socket timed out receive encrypted random sequence")
    
    if crypt_seq_cli is None:
        raise TOSDB_VirtualizationError("client failed to return encrypted sequence")

    # decrypt, compare to original, signal client 
    seq_cli = _AES.new(password, _AES.MODE_CFB, iv).decrypt(crypt_seq_cli)      
    seq_match = (rseq == seq_cli)
    try:
        rmsg = _vAUTH_SUCCESS if seq_match else _vAUTH_FAILURE
        _send_tcp(my_sock, rmsg.encode())       
    except BaseException as e:
        raise TOSDB_VirtualizationError("failed to send success/failure to client", e)

    return seq_match
Пример #8
0
 def getrandbits(self, k):
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     if k != int(k):
         raise TypeError('number of bits should be an integer')
     bytes = (k + 7) // 8
     x = long(_hexlify(_urandom(bytes)), 16)
     return x >> bytes * 8 - k
Пример #9
0
    def choice(seq):
        """Choose a random element from a non-empty sequence."""
        ceil = lambda n: int(n if (n == n//1) else (n//1)+1)
        bytebin = lambda i: '0b'+'0'*( 8*ceil((len(bin(i))-2)/8) - (len(bin(i))-2) )  +  bin(i)[2:]
        positive = lambda v: (0 if abs(v)!=v else v)
        
        length = len(seq)-1
        binary_length = len(bin(length))

        byte_count = ceil((binary_length-2)/8)
        
        random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
        random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
        
        while (random_int)>length:
            random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
            random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
        return seq[random_int]
Пример #10
0
 def getrandbits(self, k):
     """getrandbits(k) -> x.  Generates an int with k random bits."""
     if k <= 0:
         raise ValueError("number of bits must be greater than zero")
     if k != int(k):
         raise TypeError("number of bits should be an integer")
     numbytes = (k + 7) // 8  # bits / 8 and rounded up
     x = int.from_bytes(_urandom(numbytes), "big")
     return x >> (numbytes * 8 - k)  # trim excess bits
Пример #11
0
 def getrandbits(self, k):
     """getrandbits(k) -> x.  Generates a long int with k random bits."""
     if k <= 0:
         raise ValueError("number of bits must be greater than zero")
     if k != int(k):
         raise TypeError("number of bits should be an integer")
     bytes = (k + 7) // 8
     x = long(_hexlify(_urandom(bytes)), 16)
     return x >> bytes * 8 - k
 def getrandbits(self, k):
     """getrandbits(k) -> x.  Generates an int with k random bits."""
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     if k != int(k):
         raise TypeError('number of bits should be an integer')
     numbytes = (k + 7) // 8  # bits / 8 and rounded up
     x = int.from_bytes(_urandom(numbytes), 'big')
     return x >> (numbytes * 8 - k)  # trim excess bits
Пример #13
0
 def getrandbits(self, k):
     """getrandbits(k) -> x.  Generates a long int with k random bits."""
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     if k != int(k):
         raise TypeError('number of bits should be an integer')
     bytes = (k + 7) // 8                    # bits / 8 and rounded up
     x = long(_hexlify(_urandom(bytes)), 16)
     return x >> (bytes * 8 - k)             # trim excess bits
Пример #14
0
 def getrandbits(self, k):
     """getrandbits(k) -> x.  Generates a long int with k random bits."""
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     if k != int(k):
         raise TypeError('number of bits should be an integer')
     bytes = (k + 7) // 8  # bits / 8 and rounded up
     x = long(_hexlify(_urandom(bytes)), 16)
     return x >> (bytes * 8 - k)  # trim excess bits
Пример #15
0
 def getrandbits(self, k):
     if k <= 0:
         raise ValueError('number of bits must be greater than zero')
     
     if k != int(k):
         raise TypeError('number of bits should be an integer')
     
     bytes = (k + 7) // 8
     x = long(_hexlify(_urandom(bytes)), 16)
     return x >> bytes * 8 - k
Пример #16
0
    def seed(self, a=None):
        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256)

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #17
0
    def seed(self, a = None):
        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256)

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #18
0
 def seed(self, seed=None):
     if seed is None:
         # generate the seed the same way random.seed() does internally
         try:
             from os import urandom as _urandom
             seed = int.from_bytes(_urandom(2500), 'big')
         except NotImplementedError:  # pragma: no cover
             import time
             seed = int(time.time() * 256)
     random.seed(seed)
     return seed
Пример #19
0
    def choices(population, weights=None, *, cum_weights=None, k=1):
        """Return a k sized list of population elements chosen with replacement.

        If the relative weights or cumulative weights are not specified,
        the selections are made with equal probability.

        """
        ceil = lambda n: int(n if (n == n//1) else (n//1)+1)
        bytebin = lambda i: '0b'+'0'*( 8*ceil((len(bin(i))-2)/8) - (len(bin(i))-2) )  +  bin(i)[2:]
        positive = lambda v: (0 if abs(v)!=v else v)

        if weights == None and cum_weights == None:
            pop = list(population)
        elif cum_weights == None:
            pop = []
            for i in range(len(weights)):
                for n in range(weights[i]):
                    pop.append(population[i])
        else:
            pop = []
            cw = 0
            for i in range(len(weights)):
                cw += weights[i]
                for n in range(cw):
                    pop.append(population[i])

        length = len(pop)-1
        binary_length = len(bin(length))

        byte_count = ceil((binary_length-2)/8)
        output = []
        while len(output) < k:
            random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
            random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
            
            while (random_int)>length:
                random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
                random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
            if random_int not in output:
                output.append(pop[random_int])
        return output
Пример #20
0
    def normalvariate(mu, sigma):
        """Normal distribution.

        mu is the mean, and sigma is the standard deviation.

        """
        # mu = mean, sigma = standard deviation

        # Uses Kinderman and Monahan method. Reference: Kinderman,
        # A.J. and Monahan, J.F., "Computer generation of random
        # variables using the ratio of uniform deviates", ACM Trans
        # Math Software, 3, (1977), pp257-260.

        while True:
            u1 = float('0.'+str(int.from_bytes(_urandom(7), byteorder='big', signed=False) >> 3))
            u2 = 1.0 - float('0.'+str(int.from_bytes(_urandom(7), byteorder='big', signed=False) >> 3))
            z = (4 * _exp(-0.5)/(2.0**0.5))*(u1-0.5)/u2
            zz = z*z/4.0
            if zz <= -_log(u2):
                break
        return mu + z*sigma
Пример #21
0
    def randint(a, b):
        """Return random integer in range [a, b], including both end points.
        """
        ceil = lambda n: int(n if (n == n//1) else (n//1)+1)
        bytebin = lambda i: '0b'+'0'*( 8*ceil((len(bin(i))-2)/8) - (len(bin(i))-2) )  +  bin(i)[2:]
        positive = lambda v: (0 if abs(v)!=v else v)
        
        length = b-a
        binary_length = len(bin(length))

        byte_count = ceil((binary_length-2)/8)
        
        random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
        try:
            random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
        except ValueError as e:
            print(e, random_int, binary_length, length)
        
        while (random_int+a)>b:
            random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
            random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
        return random_int + a
Пример #22
0
def do_initializations():
    sys.path.insert(0, 'solutions') # to avoid needing an __init__.py in the 'solutions' directory
    if not args.seed: # do as random.py source code to generate a random seed
        try:
            from os import urandom as _urandom
            from binascii import hexlify as _hexlify
            a = long(_hexlify(_urandom(16)), 16)
        except NotImplementedError:
            import time
            a = long(time.time() * 256) # use fractional seconds
        args.seed = a
    import random 
    random.seed(args.seed)
Пример #23
0
    def sample(population, k):
        """Chooses k unique random elements from a population sequence or set.

        Returns a new list containing elements from the population while
        leaving the original population unchanged.  The resulting list is
        in selection order so that all sub-slices will also be valid random
        samples.  This allows raffle winners (the sample) to be partitioned
        into grand prize and second place winners (the subslices).

        Members of the population need not be hashable or unique.  If the
        population contains repeats, then each occurrence is a possible
        selection in the sample.

        To choose a sample in a range of integers, use range as an argument.
        This is especially fast and space efficient for sampling from a
        large population:   sample(range(10000000), 60)
        """
        ceil = lambda n: int(n if (n == n//1) else (n//1)+1)
        bytebin = lambda i: '0b'+'0'*( 8*ceil((len(bin(i))-2)/8) - (len(bin(i))-2) )  +  bin(i)[2:]
        positive = lambda v: (0 if abs(v)!=v else v)

        
        length = len(population)-1
        binary_length = len(bin(length))

        byte_count = ceil((binary_length-2)/8)

        output = []
        while len(output) < k:
            random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
            random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
            
            while (random_int)>length:
                random_int = int.from_bytes(_urandom(byte_count), byteorder='big', signed=False)
                random_int = random_int >> positive(len(bytebin(random_int))-binary_length)
            if random_int not in output:
                output.append(population[random_int])
        return output
Пример #24
0
 def seed(self, a=None, version=2):
     if a is None:
         try:
             a = int.from_bytes(_urandom(32), 'big')
         except NotImplementedError:
             import time
             a = int(time.time() * 256)
     if version == 2 and isinstance(a, (str, bytes, bytearray)):
         if isinstance(a, str):
             a = a.encode()
         a += _sha512(a).digest()
         a = int.from_bytes(a, 'big')
     super().seed(a)
     self.gauss_next = None
Пример #25
0
 def seed(self, a=None, version=2):
     if a is None:
         try:
             a = int.from_bytes(_urandom(32), 'big')
         except NotImplementedError:
             import time
             a = int(time.time()*256)
     if version == 2 and isinstance(a, (str, bytes, bytearray)):
         if isinstance(a, str):
             a = a.encode()
         a += _sha512(a).digest()
         a = int.from_bytes(a, 'big')
     super().seed(a)
     self.gauss_next = None
Пример #26
0
    def seed(self, a = None):
        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256)

        if not isinstance(a, (int, long)):
            a = hash(a)
        a, x = divmod(a, 30268)
        a, y = divmod(a, 30306)
        a, z = divmod(a, 30322)
        self._seed = (int(x) + 1, int(y) + 1, int(z) + 1)
        self.gauss_next = None
Пример #27
0
    def seed(self, a=None):
        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256)

        if not isinstance(a, (int, long)):
            a = hash(a)
        a, x = divmod(a, 30268)
        a, y = divmod(a, 30306)
        a, z = divmod(a, 30322)
        self._seed = (int(x) + 1, int(y) + 1, int(z) + 1)
        self.gauss_next = None
Пример #28
0
def randbytes(nbytes: int) -> bytes:
    r"""Return a random byte string containing *nbytes* bytes.

    Raises ValueError if nbytes <= 0, and TypeError if it's not an integer.

    >>> randbytes(16)  #doctest:+SKIP
    b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'

    """
    if not isinstance(nbytes, int):
        raise TypeError('number of bytes shoud be an integer')
    if nbytes <= 0:
        raise ValueError('number of bytes must be greater than zero')

    return _urandom(nbytes)
Пример #29
0
 def seed(self, x=None, *args):
     """For consistent cross-platform seeding, provide an integer seed.
     """
     if x is None:
         # Use same random seed code copied from Python's random.Random
         try:
             x = long(_hexlify(_urandom(16)), 16)
         except NotImplementedError:
             import time
             x = long(time.time() * 256) # use fractional seconds
     elif not isinstance(x, _Integral):
         # Use the hash of the input seed object. Note this does not give
         # consistent results cross-platform--between Python versions or
         # between 32-bit and 64-bit systems.
         x = hash(x)
     self.rng_iterator.seed(x, *args, mix_extras=True)
Пример #30
0
    def seed(self, a=None):
        # """Initialize internal state from hashable object.
        # None or no argument seeds from current time or from an operating
        # system specific randomness source if available.
        # If a is not None or an int or long, hash(a) is used instead.
        # """

        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256)  # use fractional seconds

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #31
0
    def expovariate(self, lambd):
        """Exponential distribution.

        lambd is 1.0 divided by the desired mean.  It should be
        nonzero.  (The parameter would be called "lambda", but that is
        a reserved word in Python.)  Returned values range from 0 to
        positive infinity if lambd is positive, and from negative
        infinity to 0 if lambd is negative.

        """
        # lambd: rate lambd = 1/mean
        # ('lambda' is a Python reserved word)

        # we use 1-random() instead of random() to preclude the
        # possibility of taking the log of zero.
        return -_log(1.0 - float('0.'+str(int.from_bytes(_urandom(7), byteorder='big', signed=False) >> 3)))/lambd
Пример #32
0
 def seed(self, x=None, *args):
     """For consistent cross-platform seeding, provide an integer seed.
     """
     if x is None:
         # Use same random seed code copied from Python's random.Random
         try:
             x = int(_hexlify(_urandom(16)), 16)
         except NotImplementedError:
             import time
             x = int(time.time() * 256)  # use fractional seconds
     elif not isinstance(x, _Integral):
         # Use the hash of the input seed object. Note this does not give
         # consistent results cross-platform--between Python versions or
         # between 32-bit and 64-bit systems.
         x = hash(x)
     self.rng_iterator.seed(x, *args, mix_extras=True)
Пример #33
0
    def seed(self, a=None):
        # """Initialize internal state from hashable object.
        # None or no argument seeds from current time or from an operating
        # system specific randomness source if available.
        # If a is not None or an int or long, hash(a) is used instead.
        # """

        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #34
0
    def seed(self, a=None, minstates=recstates):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or an int or long, hash(a) is used instead.

        If a is an int or long, a is used directly.  Distinct values between
        0 and 27814431486575L inclusive are guaranteed to yield distinct
        internal states (this guarantee is specific to the default
        Wichmann-Hill generator).

        This has been modified to produce infinite distinct internal states,
        or at least whatever your RAM and CPU allow for.
        The number of possible internal states will always be equal to or
        greater than the value of the seed. To change the number of possible
        internal states, call setsecurity(num_of_states) or use getsecurity()
        to see how many there are.

        The reason I modified the code to work this way is to ensure every
        unique seed generates unique output, over a large enough number of
        pseudo-random numbers generated.
        """

        if a is None:
            try:
                a = (long(_hexlify(_urandom(64)), 16)+1)*minstates
            except NotImplementedError:
                import time
                a = long(time.time()*256+1)*minstates # use units of 1/256 seconds and multiply by an insanely huge number so that you don't run into any upper boundaries

        if not isinstance(a, (int, long)):
            a = hash(a)*minstates # use the hash of the seed and multiply by an insanely huge number so that you don't run into any upper boundaries
        while abs(a) < minstates:
            a = hash(str(a))*minstates
        if a >= minstates:
	        self.setsecurity(a)
	else:
		self.setsecurity(minstates)

        a, x = divmod(a, xmod1)
        a, y = divmod(a, xmod2)
        a, z = divmod(a, xmod3)
        self._seed = int(x)+1, int(y)+1, int(z)+1

        self.gauss_next = None
def create_seed_value():
    """Creates a seed value for the `random` module, should one not be
    provided by the user.

    This code is simply a reproduction of the code from random.py in the
    standard library.

    Returns a seed value.

    """
    from binascii import hexlify as _hexlify
    from os import urandom as _urandom
    try:
        seed = long(_hexlify(_urandom(16)), 16)
    except NotImplementedError:
        import time
        seed = long(time.time() * 256) # use fractional seconds
    return seed
Пример #36
0
    def seed(self, a=None):
        """Initialize internal state of the random number generator.
        None or no argument seeds from current time or from an operating
        system specific randomness source if available.
        If a is not None or is an int or long, hash(a) is used instead.
        Hash values for some types are nondeterministic when the
        PYTHONHASHSEED environment variable is enabled.
        """

        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = long(_hexlify(_urandom(2500)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #37
0
    def seed(self, a=None):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or an int or long, hash(a) is used instead.
        """

        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = long(_hexlify(_urandom(2500)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #38
0
    def seed(self, a=None, version=2):
        from os import urandom as _urandom
        from hashlib import sha512 as _sha512
        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = int.from_bytes(_urandom(2500), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256)  # use fractional seconds

        if version == 2:
            if isinstance(a, (str, bytes, bytearray)):
                if isinstance(a, str):
                    a = a.encode()
                a += _sha512(a).digest()
                a = int.from_bytes(a, 'big')

        self._current_seed = a
        super().seed(a)
Пример #39
0
    def seed(self, a=None, version=2):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If *a* is an int, all bits are used.

        For version 2 (the default), all of the bits are used if *a* is a str,
        bytes, or bytearray.  For version 1 (provided for reproducing random
        sequences from older versions of Python), the algorithm for str and
        bytes generates a narrower range of seeds.

        """

        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = int.from_bytes(_urandom(2500), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256)  # use fractional seconds

        if version == 1 and isinstance(a, (str, bytes)):
            x = ord(a[0]) << 7 if a else 0
            for c in a:
                x = ((1000003 * x) ^ ord(c)) & 0xFFFFFFFFFFFFFFFF
            x ^= len(a)
            a = -2 if x == -1 else x

        if version == 2:
            if isinstance(a, (str, bytes, bytearray)):
                if isinstance(a, str):
                    a = a.encode()
                a += _sha512(a).digest()
                a = int.from_bytes(a, 'big')

        super().seed(a)
        self.gauss_next = None
Пример #40
0
    def seed(self, a=None, version=2):
        """Initialize internal state from hashable object.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If *a* is an int, all bits are used.

        For version 2 (the default), all of the bits are used if *a* is a str,
        bytes, or bytearray.  For version 1 (provided for reproducing random
        sequences from older versions of Python), the algorithm for str and
        bytes generates a narrower range of seeds.

        """

        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = int.from_bytes(_urandom(2500), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256) # use fractional seconds

        if version == 1 and isinstance(a, (str, bytes)):
            x = ord(a[0]) << 7 if a else 0
            for c in a:
                x = ((1000003 * x) ^ ord(c)) & 0xFFFFFFFFFFFFFFFF
            x ^= len(a)
            a = -2 if x == -1 else x

        if version == 2:
            if isinstance(a, (str, bytes, bytearray)):
                if isinstance(a, str):
                    a = a.encode()
                a += _sha512(a).digest()
                a = int.from_bytes(a, 'big')

        super().seed(a)
        self.gauss_next = None
Пример #41
0
    def seed(self, a=None):
        """Initialize internal state of the random number generator.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If a is not None or is an int or long, hash(a) is used instead.
        Hash values for some types are nondeterministic when the
        PYTHONHASHSEED environment variable is enabled.
        """

        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = int(_hexlify(_urandom(2500)), 16)
            except NotImplementedError:
                import time
                a = int(time.time() * 256) # use fractional seconds

        super(Random, self).seed(a)
        self.gauss_next = None
Пример #42
0
    def triangular(low=0.0, high=1.0, mode=None):
        """Triangular distribution.

        Continuous distribution bounded by given lower and upper limits,
        and having a given mode value in-between.

        http://en.wikipedia.org/wiki/Triangular_distribution

        """
        sqrt = lambda s: s**0.5
        try:
            c = 0.5 if mode is None else (mode - low) / (high - low)
        except ZeroDivisionError:
            return low

        random_float = float('0.'+str(int.from_bytes(_urandom(7), byteorder='big', signed=False) >> 3)) # 40% faster than dividing by 10**16
        
        if random_float > c:
            random_float = 1.0 - random_float
            c = 1.0 - c
            low = high
            high = low
        return low + (high - low) * sqrt(random_float * c)
Пример #43
0
 def seed(self, a=None):
     """Initialize internal state from hashable object.
         
         None or no argument seeds from current time or from an operating
         system specific randomness source if available.
         
         If a is not None or an int or long, hash(a) is used instead.
         
         If a is an int or long, a is used directly.  Distinct values between
         0 and 27814431486575L inclusive are guaranteed to yield distinct
         internal states (this guarantee is specific to the default
         Wichmann-Hill generator).
         """
     
     if a is None:
         try:
             a = long(_hexlify(_urandom(16)), 16)
         except NotImplementedError:
             import time
             a = long(time.time() * 256) # use fractional seconds
     
     if not isinstance(a, (int, long)):
         a = hash(a)
Пример #44
0
 def randbytes(self, n):
     """Generate n random bytes."""
     # os.urandom(n) fails with ValueError for n < 0
     # and returns an empty bytes string for n == 0.
     return _urandom(n)
Пример #45
0
 def random(self):
     """Get the next random number in the range [0.0, 1.0)."""
     return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF
Пример #46
0
 def random(self):
     """Get the next random number in the range [0.0, 1.0)."""
     return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Пример #47
0
import time
import sys

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "  script requires input of number of random seeds to generate"
        sys.exit(1)

    print sys.argv[1]
    nrandom = int(sys.argv[1])
    #nrandom = 100

    # generate input number of random integers and write them into seed file
    aran = [0]*nrandom
    rs = file("ranseeds.dat","w")
    for i in range(nrandom):
        try:     
            a = struct.unpack("I",_urandom(4)) # get 4 bytes of randomness
        except:
            raise NotImplementedError('system random numbers are not available')
        
        a2 = int(time.time() * 256) # fractional seconds DO NOT USE for parallel applications
        aran[i] =a[0]
        print a[0], a2
        print >>rs, a[0]
    
    rs.close()



Пример #48
0
 def random(self):
     return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Пример #49
0
 def random(self):
     return (int.from_bytes(_urandom(7), 'big') >> 3)*RECIP_BPF
Пример #50
0
 def random(self):
     """Get the next random number in the range [0.0, 1.0)."""
     return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF
Пример #51
0
 def random(self):
     """Get the next random number in the range [0.0, 1.0)."""
     return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Пример #52
0
    def random(self):
        """Get the next random number in the range [0.0, 1.0)."""
        return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF

    def getrandbits(self, k):
        """getrandbits(k) -> x.  Generates an int with k random bits."""
        if k <= 0:
            raise ValueError('number of bits must be greater than zero')
<<<<<<< HEAD
        if k != int(k):
            raise TypeError('number of bits should be an integer')
=======
>>>>>>> 716b15a33aed978ded8a6bde17855cb6c6aa7f78
        numbytes = (k + 7) // 8                       # bits / 8 and rounded up
        x = int.from_bytes(_urandom(numbytes), 'big')
        return x >> (numbytes * 8 - k)                # trim excess bits

    def seed(self, *args, **kwds):
        "Stub method.  Not used for a system random number generator."
        return None

    def _notimplemented(self, *args, **kwds):
        "Method should not be called for a system random number generator."
        raise NotImplementedError('System entropy source does not have state.')
    getstate = setstate = _notimplemented

## -------------------- test program --------------------

def _test_generator(n, func, args):
    import time
Пример #53
0
 def random(self):
     return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Пример #54
0
 def random(self):
     return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF