def mpi_to_long(mpi_byte_string): """ Converts an OpenSSL-format MPI Bignum byte string into a long. :param mpi_byte_string: OpenSSL-format MPI Bignum byte string. :returns: Long value. """ #Make sure this is a positive number assert (ord(mpi_byte_string[4]) & 0x80) == 0 byte_array = bytes_to_bytearray(mpi_byte_string[4:]) return bytearray_to_long(byte_array)
def bytes_to_long_original(byte_string): """ Convert a byte string to a long integer:: bytes_to_long(byte_string) : long This is (essentially) the inverse of long_to_bytes(). :param byte_string: A byte string. :returns: Long. """ byte_array = bytes_to_bytearray(byte_string) return bytearray_to_long(byte_array)
def generate_random_long(low, high): """ Generates a random long integer. :param low: Low :param high: High :returns: Random long integer value. """ if low >= high: raise ValueError("High must be greater than low.") num_bits = bit_count(high) num_bytes = byte_count(high) last_bits = num_bits % 8 while 1: byte_array = generate_random_bytearray(num_bytes) if last_bits: byte_array[0] = byte_array[0] % (1 << last_bits) n = bytearray_to_long(byte_array) if n >= low and n < high: return n