Example #1
0
 def _generate_x(self):
     # generate an "x" (1 < x < q), where q is (p-1)/2.
     # p is a 128-byte (1024-bit) number, where the first 64 bits are 1.
     # therefore q can be approximated as a 2^1023.  we drop the subset of
     # potential x where the first 63 bits are 1, because some of those
     # will be larger than q (but this is a tiny tiny subset of
     # potential x).
     while 1:
         x_bytes = os.urandom(128)
         x_bytes = byte_mask(x_bytes[0], 0x7f) + x_bytes[1:]
         if (x_bytes[:8] != b7fffffffffffffff and
                 x_bytes[:8] != b0000000000000000):
             break
     self.x = util.inflate_long(x_bytes)
Example #2
0
 def _generate_x(self):
     # generate an "x" (1 < x < (p-1)/2).
     q = (self.p - 1) // 2
     qnorm = util.deflate_long(q, 0)
     qhbyte = byte_ord(qnorm[0])
     byte_count = len(qnorm)
     qmask = 0xff
     while not (qhbyte & 0x80):
         qhbyte <<= 1
         qmask >>= 1
     while True:
         x_bytes = os.urandom(byte_count)
         x_bytes = byte_mask(x_bytes[0], qmask) + x_bytes[1:]
         x = util.inflate_long(x_bytes, 1)
         if (x > 1) and (x < q):
             break
     self.x = x
Example #3
0
def _roll_random(n):
    """returns a random # from 0 to N-1"""
    bits = util.bit_length(n - 1)
    byte_count = (bits + 7) // 8
    hbyte_mask = pow(2, bits % 8) - 1

    # so here's the plan:
    # we fetch as many random bits as we'd need to fit N-1, and if the
    # generated number is >= N, we try again.  in the worst case (N-1 is a
    # power of 2), we have slightly better than 50% odds of getting one that
    # fits, so i can't guarantee that this loop will ever finish, but the odds
    # of it looping forever should be infinitesimal.
    while True:
        x = os.urandom(byte_count)
        if hbyte_mask > 0:
            x = byte_mask(x[0], hbyte_mask) + x[1:]
        num = util.inflate_long(x, 1)
        if num < n:
            break
    return num