Exemplo n.º 1
0
def produce_results():
    test_AF, test_LD = loadPriorKnowledge(
        "E:/Lab/LCA1/honeygenes/dat/hg_allele_freqs_chr22_CEU.txt",
        "E:/Lab/LCA1/honeygenes/dat/hg_ld_chr22_CEU.txt")

    SNPRefList = []
    dataset = []
    datFile = open("E:/Lab/LCA1/honeygenes/dat/new_genotypes_chr22_CEU.txt")
    for line in datFile.readlines():
        attrArray = line.split()
        SNPRefList.append(attrArray[0])
        dataset.append(attrArray[1:])


#    SNPRefList = SNPRefList[0:100]
    dataset = np.array(dataset, dtype=int)
    #    bitLen1 = int(math.ceil(len(SNPRefList)*math.log(3,2)))
    maxNaiveSeed = 3**len(SNPRefList) - 1
    bitLen2 = int(math.ceil(len(SNPRefList) * 3))
    for i in range(len(SNPRefList)):
        powOfThree.append(mpz(3)**mpz(i))

    sec_exp_result = open('sec_exp_result_large.txt', 'w')
    pInd = 16
    while pInd < 17:
        pInd += 1
        correctSize = gmpy2.log2(
            intervalSize(list(dataset[:, pInd]), SNPRefList, test_AF, test_LD,
                         bitLen2))
        numOfExps = 1000
        sizes1 = [0] * numOfExps
        for i in range(numOfExps):
            randomSeed1 = random.randint(0, maxNaiveSeed)
            randomSeq1 = naiveDecode(randomSeed1, SNPRefList, test_AF, test_LD,
                                     maxNaiveSeed)
            sizes1[i] = gmpy2.log2(
                intervalSize(randomSeq1, SNPRefList, test_AF, test_LD,
                             bitLen2))
            print sizes1[i]
        print ', '.join(map(str, sizes1))

        sizes2 = [0] * numOfExps
        for i in range(numOfExps):
            randomSeed2 = random.randint(0, 2**bitLen2 - 1)
            sizes2[i] = gmpy2.log2(
                intervalSize2(randomSeed2, SNPRefList, test_AF, test_LD,
                              bitLen2))
        print ', '.join(map(str, sizes2))
        sec_exp_result.write(str(correctSize) + '\n')
        sec_exp_result.write('\t'.join(map(str, sizes1)) + '\n')
        sec_exp_result.write('\t'.join(map(str, sizes2)) + '\n')
    sec_exp_result.close()
Exemplo n.º 2
0
def aks_test(n):
    """
    Implement the AKS primality test.
    """
    get_context().precision = bit_length(n)
    # Check if n is a perfect power. If so, return composite.
    if is_power(n):
        return "composite"

    # Find the smallest r such that the multiplicative order of n modulo r
    # is greater than log(n, 2)^2
    r = get_r(n)

    # If 1 < gcd(a, n) < n for some a <= r, return composite
    for a in range(1, r):
        if gcd(a, n) > 1 and gcd(a, n) < n:
            return "composite"

    # If n <= r, return prime
    if n <= r:
        return "prime"

    # Check if (x + a)^n mod (x^r - 1, n) != (x^n + a) mod (x^r - 1, n)
    if False in ray.get([
            is_congruent.remote(a, n, r)
            for a in range(1, mpz(floor(sqrt(phi(r)) * log2(n))))
    ]):
        return "composite"

    return "prime"
Exemplo n.º 3
0
def good_pair(p, q):
    """Returns p*q if p and q are a good pair, else 0."""
    n = p * q
    k = gmpy2.ceil(gmpy2.log2(n))
    if abs(p - q) > 2**(k / 2 - 100):
        return n
    return 0
Exemplo n.º 4
0
def check_pair(p: int, q: int) -> Tuple[int, int]:
    """Returns the encryption modulus and totient for the given primes."""
    n = p*q
    k = ceil(log2(n))
    if abs(p - q) > 2**(k/2 - 100):
        return n, n - (p + q - 1)
    return 0, 0
Exemplo n.º 5
0
def solve(*lines):
    P, Q = lines
    Q = mpz(Q)
    P = mpz(P)
    _gcd = gcd(P, Q)
    if gcd > 1:
        P = c_div(P, _gcd)
        Q = c_div(Q, _gcd)
    if not log2(Q).is_integer():
        return 'impossible'
    res = log2(P)
    res = mpz(floor(res))
    res, rem = c_divmod(Q, 2**res)
    if rem:
        return 'impossible'
    return int(log2(res))
Exemplo n.º 6
0
def bits_in_number(number):
    """
    Returns number of bits in the given number
    :param number: long number
    """
    if number == 0:
        return 0
    return gmpy2.mpz(gmpy2.floor(gmpy2.log2(number)) + 1)
Exemplo n.º 7
0
def p_to_entropy(p01, p10, bitwidth):
    smp = mpfr('0.0')

    mcv_prob, mcv = symbol_max_probability(p01, p10, bitwidth)

    ent = -gmpy2.log2(mcv_prob)
    #printf("XXX entropy = %f  p01=%f, p10=%f\n",ent,p01,p10);
    return ent / bitwidth, mcv_prob, mcv
Exemplo n.º 8
0
def p_to_entropy(p01, p10, bitwidth, verbose=False):
    smp = mpfr('0.0')

    mcv_prob, mcv = symbol_max_probability(p01, p10, bitwidth)

    ent = -gmpy2.log2(mcv_prob)
    #printf("XXX entropy = %f  p01=%f, p10=%f",ent,p01,p10,file=sys.stderr)
    return ent / bitwidth, mcv_prob, mcv
Exemplo n.º 9
0
def ecm(N: int):
    """

    Elliptic-curve factorization method

    Args:
        N (int): target

    Returns:
        int: factor
    """
    L = int(gmpy2.log2(N)**2 + gmpy2.log2(N) * 0.25)
    iter_count = 0

    while True:
        a = gmpy2.mpz(random.randint(0, N))
        x = gmpy2.mpz(random.randint(0, N))
        y = gmpy2.mpz(random.randint(0, N))

        ECMPoint.init(a, N)
        P = ECMPoint(x, y)

        prime = gmpy2.mpz(2)

        while prime <= L:
            base = copy.copy(P)
            exponent = gmpy2.mpz(logn(L, prime))
            M = pow(prime, exponent)
            prime = next_prime(prime)

            M -= 1
            while M > 0:
                if M % 2 == 1:
                    add_rslt = P.add(base)
                    if not add_rslt:
                        return ecm_calc_factor(P, base, N)
                add_rslt = base.add(base)
                if not add_rslt:
                    return ecm_calc_factor(base, base, N)
                M //= 2
        iter_count += 1
Exemplo n.º 10
0
 def compute_parameters(self, orwell_file):
     data_prob = 0.0
     total_count = 0
     for token_list in self.data_parser.iterate_line(orwell_file):
         total_count += 1
         sent_len = len(token_list) - 1
         sent_prob = self.sent_prob(sent_len)
         data_prob += gmpy2.log2(sent_prob)
     log_data        = (data_prob / total_count)
     perplexity      = math.pow(2, (-1.0 * log_data))
     cross_entropy   = math.log(perplexity, 2)
     return cross_entropy, perplexity
Exemplo n.º 11
0
def check_modulus_size(n):
    # type: (int) -> RE
    """
    Checks if the modulus has good RSA sizes

    :n The RSA modulus
    """
    # TODO: Research exact size

    if gmpy2.log2(n) < 1023:
        return RSAResult.SMALL_MODULUS
    return RSAResult.OK
Exemplo n.º 12
0
def find_composite():
    """
    Historically the mersenne.org manual results didn't mark as complete
    ranges that included a composite result.
    e.g. https://www.mersenne.org/report_exponent/?exp_lo=113644673&full=1

    Search for any result that contained 1 or more composite factor and save
        <factor>
        <factor>
        found <x> factor for M<z> from 2^72 to 2^73 [mfaktc 0.21 barrett76_mul32_gs]
    """

    # results[exp][bitlevel] = []
    results = defaultdict(lambda: defaultdict(list))

    # set of (exp, bitlevels) that will need to be resubmitted
    composite = set()

    assert os.path.isfile(RESULTS_FILE), RESULTS_FILE
    with open(RESULTS_FILE) as results_file:
        for result in results_file:
            match = re.match("M([0-9]*) has a factor: ([0-9]*).*TF:..:([0-9]{2})", result)
            if match:
                M, factor, upper_tf = map(int, match.groups())
                # Wonky factor, see https://www.mersenneforum.org/showthread.php?p=585014#post585014
                if factor == 147602823780943516039:
                    continue

                # Composite factor
                if not gmpy2.is_prime(factor):
                    results[M][upper_tf].append(result)
                    log2 = gmpy2.log2(factor)
                    assert (upper_tf - 1) < log2 < upper_tf, (factor, log2, upper_tf)
                    composite.add( (M, upper_tf) )

            match = re.match("found [1-9]+ factors? for M([0-9]+) from 2\^([0-9]+) to 2\^([0-9]+)", result)
            if match:
                # Assumes that mfaktc was run with StopAfterFactor=0 (which is was
                M, low, high = map(int, match.groups())
                results[M][high].append(result)

    print ()
    print ("{} compsite factors found, {} exponents {} bit levels".format(
        len(composite), len(results), sum(map(len, results.values()))))
    print ()

    for M, high in sorted(composite):
        if high <= 68:
            continue
        #print (f"\t# M{M} 2^{high-1} to 2^{high}")
        for result in results[M][high]:
            print (result.strip())
Exemplo n.º 13
0
def is_good_pair(p: int, q: int) -> Optional[Tuple[int, int]]:
    """Returns the encryption modulus and totient for the given primes.
    :param p: One of the two primes to be used for encryption.
    :type p: int
    :param q: The other prime used for encryption.
    :type q: int
    :returns: Either the encryption modulus and the totient, or None.
    :rtype: Optional[Tuple[int, int]]"""
    n = p*q
    k = gmpy2.ceil(gmpy2.log2(n))
    if abs(p - q) > 2**(k/2 - 100):
        return n, n - (p + q - 1)
    return None
Exemplo n.º 14
0
def get_r(n):
    """
    Find the smallest r such that the multiplicative order of n modulo r
    is greater than log(n, 2)^2. If r and n are not coprime, skip this r.
    """
    r = 2
    while True:
        if gcd(r, n) != 1:
            r += 1
        elif ord(n, r) > pow(log2(n), 2):
            break
        else:
            r += 1

    return r
Exemplo n.º 15
0
def produce_results():
    test_AF, test_LD = loadPriorKnowledge(
        "E:/Lab/LCA1/honeygenes/dat/hg_allele_freqs_chr22_CEU.txt",
        "E:/Lab/LCA1/honeygenes/dat/hg_ld_chr22_CEU.txt")

    SNPRefList = []
    dataset = []
    datFile = open("E:/Lab/LCA1/honeygenes/dat/new_genotypes_chr22_CEU.txt")
    for line in datFile.readlines():
        attrArray = line.split()
        SNPRefList.append(attrArray[0])
        dataset.append(attrArray[1:])
#    SNPRefList = SNPRefList[0:100]
    dataset = np.array(dataset, dtype=int)
    #    bitLen1 = int(math.ceil(len(SNPRefList)*math.log(3,2)))
    maxNaiveSeed = 3**len(SNPRefList) - 1
    bitLen2 = int(math.ceil(len(SNPRefList) * 3))
    for i in range(len(SNPRefList)):
        powOfThree.append(mpz(3)**mpz(i))

    for i in range(50):
        print gmpy2.log2(
            intervalSize(list(dataset[:, i]), SNPRefList, test_AF, test_LD,
                         bitLen2))
Exemplo n.º 16
0
def compute_cross_entropy_perplexity(obj_model, data_file):
    obj_model.logger.info("Started analysing data file %s to compute cross entropy" % data_file)
    data_prob  = 0.0
    word_count = 0
    for token_list in obj_model.data_parser.iterate_line(data_file):
        word_count += len(token_list)
        sent_prob   = obj_model.sentence_probability(token_list)
        if sent_prob is None:
            return None
        data_prob  += gmpy2.log2(sent_prob)
    obj_model.logger.info("Data Probability : %.10f" % data_prob)
    log_data        = (data_prob / word_count)
    obj_model.logger.info("Log Data         : %.10f" % log_data)
    perplexity      = math.pow(2, (-1.0 * log_data))
    obj_model.logger.info("Perplexity       : %.10f" % perplexity)
    cross_entropy   = math.log(perplexity, 2)
    obj_model.logger.info("Cross Entropy    : %.10f" % cross_entropy)
    return cross_entropy, perplexity
Exemplo n.º 17
0
 def checkPQDistance(self, keys):
     if not isinstance(keys, (tuple, list)):
         keys = [keys]
     ctx = gmpy2.get_context()
     ctx.precision = 5000
     ctx.round = gmpy2.RoundDown
     ctx.real_round = gmpy2.RoundDown
     gmpy2.set_context(ctx)
     for key in keys:
         gmpy_key = gmpy2.mpfr(key)
         skey = int(gmpy2.sqrt(gmpy_key))
         skey2 = skey ** 2
         if (skey2 > key) or (((skey + 1) ** 2) < key):
             print skey2
             print (skey+1)**2
             raise Exception("WTF")
         bits = int(gmpy2.log2(key - skey2))
         if bits < 480:
             print '%d Has p, q distance of %d bits' % (key, bits)
Exemplo n.º 18
0
 def checkPQDistance(self, keys):
     if not isinstance(keys, (tuple, list)):
         keys = [keys]
     ctx = gmpy2.get_context()
     ctx.precision = 5000
     ctx.round = gmpy2.RoundDown
     ctx.real_round = gmpy2.RoundDown
     gmpy2.set_context(ctx)
     for key in keys:
         gmpy_key = gmpy2.mpfr(key)
         skey = int(gmpy2.sqrt(gmpy_key))
         skey2 = skey**2
         if (skey2 > key) or (((skey + 1)**2) < key):
             print skey2
             print(skey + 1)**2
             raise Exception("WTF")
         bits = int(gmpy2.log2(key - skey2))
         if bits < 480:
             print '%d Has p, q distance of %d bits' % (key, bits)
Exemplo n.º 19
0
def to_bin(num, working_base=WORKING_BASE):
    """
    to_bin(num) -> int(bin_num)

    Calculates the binary of num.

    @param        num(int) -> A number.
    @param        working_base(int) -> num's base.
    @return        bin_num(int) -> num's binary value.
    """

    # Initialize.
    bin_num = 0

    # Finding the closest power of 2 to num. Then summerizing
    # the binary value of num and decreasing num until it's zero.
    while num > 0:
        bin_digit = int(gmpy2.log2(num))
        bin_num += working_base**bin_digit
        num -= BINARY**bin_digit

    return bin_num
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments
    
    parser = argparse.ArgumentParser(description="Generate BBS parameters.")
    
    parser.add_argument("input_file", help="""JSON file containing the seed used for generating the pseudo strong 
                                              strong prime (the name is "seed"). The required
                                              quantity of entropy it should contain depends on bitsize. As a rule of
                                              thumb the seed should contain at least 4*bitsize bits of entropy.""")
    parser.add_argument("output_file", help="""Output JSON file where this script will write the two generated strong
                                               strong primes "p" and "q". The output file should not exist already.""")
    parser.add_argument("min_prime_bitsize", type=int, help="minimum strong strong prime bit size (e.g. 2048).")
    
    args = parser.parse_args()

    
    # Check arguments
    
    output_file = args.output_file
    if os.path.exists(output_file):
        utils.exit_error("The output file '%s' already exists. Exiting."%(output_file))


    # Declare a few important variables
        
    min_prime_bitsize = args.min_prime_bitsize

    input_file = args.input_file
    with open(input_file, "r") as f:
        data = json.load(f)        
    seed = int(data["seed"])
    seed_upper_bound = int(data["seed_upper_bound"])
    approx_seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))

    utils.colprint("Minimum strong strong prime size:", str(min_prime_bitsize))
    utils.colprint("Approximate seed entropy:", str(approx_seed_entropy))

    
    # Precomputations

    first_primes = [2]                     # List of the first primes
    PI = 2                                 # Product of the primes in "first_primes"
    strong_strong_integers = [[1]]         # strong_strong_integers[i] is the list of all strong strong integers modulo
                                           # first_primes[i]
    number_of_strong_strong_integers = [1] # number_of_strong_strong_integers[i] is the number of elements of the list
                                           # strong_strong_integers[i]
    C = 1                                  # Product of the elements of "number_of_strong_strong_integers"
    
    while not 2**(min_prime_bitsize-2) < PI:
        p = int(gmpy2.next_prime(first_primes[-1]))
        first_primes.append(p)
        PI *= p
        ssi = [c for c in range(p) if is_strong_strong_basis(c, p)]
        strong_strong_integers.append(ssi)
        number_of_strong_strong_integers.append(len(ssi))
        C *= len(ssi)

    utils.colprint("Number of primes considered:", str(len(first_primes)))
    utils.colprint("Number of strong strong integers to choose from:", "about 2^%f"%(gmpy2.log2(C)))

    
    # Check that the seed is long enough

    if seed_upper_bound < C**2 * (1 << (2 * min_prime_bitsize)):
        utils.exit_error("The seed does not contain the required entropy.")

        
    # Precomputations for the CRT

    mu    = [gmpy2.divexact(PI,p) for p in first_primes]
    delta = [gmpy2.invert(x,y) for x,y in zip(mu,first_primes)]
    gamma = [gmpy2.mul(x,y) for x,y in zip(mu,delta)]


    # Generate the first strong prime
    
    print("Generating the first strong strong prime...")
    (p,seed) = generate_strong_strong_prime(seed,
                                            min_prime_bitsize,
                                            strong_strong_integers,
                                            number_of_strong_strong_integers,
                                            gamma,
                                            PI)
    utils.colprint("\tThis is the first strong strong prime:", str(p))

    
    # Generate the second strong prime
    
    print("Generating the second strong strong prime...")
    (q,seed) = generate_strong_strong_prime(seed,
                                            min_prime_bitsize,
                                            strong_strong_integers,
                                            number_of_strong_strong_integers,
                                            gamma,
                                            PI)
    utils.colprint("\tThis is the second strong strong prime:", str(q))

    
    # Generate the BBS start

    print("Generating the BBS starting point...")    
    n = p*q
    s = seed % n
    while s == 0 or s == 1 or s == p or s == q:
        s = (s+1) % n
    s0 = (s**2) % n
    utils.colprint("\tThis is the starting point s0 of BBS:", str(s0))

    
    # Save p,q, and s to the output_file

    print("Saving p,q, and s0 to %s"%(output_file))
    with open(output_file, "w") as f:
        json.dump({"bbs_p": int(p), 
                   "bbs_q": int(q), 
                   "bbs_s": int(s0)}, 
                  f,
                  sort_keys=True)
Exemplo n.º 21
0
def parse_and_print(filenames):
    # For polyfit of composite, prime
    timings = defaultdict(list)

    for fn in filenames:
        base, ext = os.path.splitext(fn)
        if ext == ".txt":
            pfgw_fn = min([
                fn2
                for fn2 in filenames if fn2.startswith(base) and '.pfgw' in fn2
            ],
                          default="")
            gmp_fn = min([
                fn2
                for fn2 in filenames if fn2.startswith(base) and '.gmp' in fn2
            ],
                         default="")
            print()
            print(f"{fn:25} | pfgw: {pfgw_fn:33} gmp: {gmp_fn}")

            if gmp_fn and pfgw_fn:
                with open(fn) as bf:
                    blines = list(map(str.strip, bf.readlines()))

                with open(gmp_fn) as gf:
                    glines = list(map(str.strip, gf.readlines()))

                with open(pfgw_fn) as pf:
                    plines = list(map(str.strip, pf.readlines()))

                rows = []
                for line in blines:
                    if not line: continue

                    match = POWER_RE.search(line)
                    match = match or PRIMORIAL_RE.search(line)
                    assert match, line
                    number, part, add = match.groups()

                    alt_number = number.replace("# +", "# + ").replace(
                        "# -", "# + -")

                    g_line = min(
                        [g for g in glines if number in g or alt_number in g],
                        default="")
                    p_line = min([p for p in plines if number in p],
                                 default="")
                    if not g_line or not p_line:
                        print(number, "NOT FOUND")
                        break
                    g_s = TIME_RE.search(g_line).group(0)
                    p_s = TIME_RE.search(p_line).group(0)
                    status = "prime" if "prime" in g_line else "composite"

                    #print (number)
                    #print (g_line)
                    #print (p_line)
                    #print (g_s, p_s)

                    bits = round(
                        gmpy2.log2(10**int(part) if '10^' in
                                   number else gmpy2.primorial(int(part))))
                    ratio = round(float(g_s) / (float(p_s) + 1e-4), 1)

                    rows.append((number, bits, status, p_s, g_s, ratio))

                    timings["gmp_" + status].append(
                        (float(bits * math.log(2)), float(g_s)))
                    timings["pfgw_" + status].append(
                        (float(bits * math.log(2)), float(p_s)))

                print()
                print(header)
                print(seperator)
                for row in rows:
                    print(columns.format(*row))
                print()
    return timings
Exemplo n.º 22
0
def _ilog2_gmpy(n):
   return int(gmpy.log2(n))
Exemplo n.º 23
0
#import matplotlib.pyplot as plt
import os
import bisect
from numpy import linspace
# gmpy2 precision initialization
BITS = (1 << 10)
BYTES = BITS/8
gmpy2.get_context().precision = BITS # a whole lotta bits

def random():
    seed = int(os.urandom(BYTES).encode('hex'), 16)
    return gmpy2.mpfr_random(gmpy2.random_state(seed))

# Useful constants as mpfr
PI = gmpy2.acos(-1)
LOG2E = gmpy2.log2(gmpy2.exp(1))
LN2 = gmpy2.log(2)
# Same, as 192.64 fixedpoint
FX_PI = int(PI * 2**64)
FX_LOG2E = int(LOG2E * 2**64)
FX_LN2 = int(LN2 * 2**64)
FX_ONE = 1 << 64
## The index of a poly is the power of x,
## the val at the index is the coefficient.
##
## An nth degree poly is a list of len n + 1.
##
## The vals in a poly must all be floating point
## numbers.

def poly_add(p1, p2):
Exemplo n.º 24
0
def good_pair(p: int, q: int) -> int:
    n = p * q
    k = gmpy2.ceil(gmpy2.log2(n))
    if abs(p - q) > 2**(k / 2 - 100):
        return n
    return 0
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments
    
    parser = argparse.ArgumentParser(description="From a table of draws, output a seed of appropriate length.")

    parser.add_argument("input_draw_file", help="""Text file with draws.""")
    parser.add_argument("output_seed_file", help="""JSON file where we can store the seed computed from the draws.""")
    parser.add_argument("entropy_to_gather", help="""Minimum entropy to extract before drawing lone bits.""")
    parser.add_argument("--nbr_lone_bits", type=int, help="""Number of lone bits to extract.""", default=0)
    
    args = parser.parse_args()


    # Check arguments
    
    output_seed_file = args.output_seed_file
    if os.path.exists(output_seed_file):
        utils.exit_error("The output file '%s' already exists. Exiting."%(output_seed_file))


    # Declare a few important variables
    
    two_pow_entropy_to_gather = (1<<int(args.entropy_to_gather))
    
    seed = 0
    L = 1 # before lone bits are drawn, seed lies in [0,L - 1]

    lone_bits_part = 0
    nbr_lone_bits = args.nbr_lone_bits


    # Scan the input file, construct the seed
    
    with open(args.input_draw_file, "r") as f:
        
        for line in f:

            if not line or line.strip() == "" or line.startswith("#"):
                continue

            (draw_id, m, n, draw) = re.split("\s+", line.strip(), maxsplit=3)

            if draw == "None":
                continue
            
            m = int(m)
            n = int(n)
            draw = [ int(x) for x in draw.split(",") ]
            index = index_from_draw(draw,m)

            if L < two_pow_entropy_to_gather:
                
                print("Draw %s used to extract entropy"%(draw_id))
                seed = gmpy2.bincoef(n,m)*seed + index
                L *= gmpy2.bincoef(n,m)
                
            else:
                
                print("Draw %s used to extract a lone bit"%(draw_id))
                b = index & 1
                seed += L * (b << (args.nbr_lone_bits - nbr_lone_bits))
                nbr_lone_bits -= 1

            if L >= two_pow_entropy_to_gather and nbr_lone_bits == 0:
                break

    if nbr_lone_bits > 0 or L < two_pow_entropy_to_gather:
        utils.exit_error("There wasn't enough draws to collect to request quantity of entropy and lone bits.")

    seed_upper_bound = L * 2**(args.nbr_lone_bits)
    seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))
    print("The seed contains more than %d bits of entropy (including the %s lone bits)."%(seed_entropy,args.nbr_lone_bits))
    print("The seed is %d"%(seed))

    print("Saving the seed to %s"%(output_seed_file))
    with open(output_seed_file, "w") as f:
        json.dump({"seed": int(seed),
                   "seed_upper_bound": int(seed_upper_bound),
                   "approx_seed_entropy": int(seed_entropy),
                   "lone_bits": int(args.nbr_lone_bits)}, 
                  f,
                  sort_keys=True)
Exemplo n.º 26
0
Arquivo: aks.py Projeto: gA4ss/MyAKS
def is_prime_by_AKS(n):
    """
    使用AKS算法确定n是否是一个素数
    True:n是素数
    False:n是合数
    """
    def __is_integer__(n):
        """
        判断一个数是否是整数
        """
        i = gmpy2.mpz(n)
        f = n - i
        return not f

    def __phi__(n):
        """
        欧拉函数,测试小于n并与n互素的个数
        """
        res = gmpy2.mpz(n)
        a = gmpy2.mpz(n)
        for i in range(2, a + 1):
            if a % i == 0:
                res = res // i * (i - 1)
                while a % i == 0:
                    a //= i
        if a > 1:
            res = res // a * (a - 1)
        return res

    def __gcd__(a, b):
        """
        计算a b的最大公约数
        """
        if b == 0:
            return a
        return __gcd__(gmpy2.mpz(b), gmpy2.mpz(a) % gmpy2.mpz(b))

    print("步骤1, 确定%d是否是纯次幂" % n)
    for b in range(2, gmpy2.mpz(gmpy2.floor(gmpy2.log2(n))) + 1):
        a = n**(1 / b)
        if __is_integer__(a):
            return False

    print("步骤2,找到一个最小的r,符合o_r(%d) > (log%d)^2" % (n, n))
    maxk = gmpy2.mpz(gmpy2.floor(gmpy2.log2(n)**2))
    maxr = max(3, gmpy2.mpz(gmpy2.ceil(gmpy2.log2(n)**5)))
    nextR = True
    r = 0
    for r in range(2, maxr):
        if nextR == False:
            break
        nextR = False
        for k in range(1, maxk + 1):
            if nextR == True:
                break
            nextR = (gmpy2.mpz(n**k % r) == 0) or (gmpy2.mpz(n**k % r) == 1)
    r = r - 1  # 循环多增加了一层
    print("r = %d" % r)

    print("步骤3,如果 1 < gcd(a, %d) < %d,对于一些 a <= %d, 输出合数" % (n, n, r))
    for a in range(r, 1, -1):
        g = __gcd__(a, n)
        if g > 1 and g < n:
            return False

    print("步骤4,如果n=%d <= r=%d,输出素数" % (n, r))
    if n <= r:
        return True

    print("步骤5")
    print("遍历a从1到\sqrt{\phi(r=%d)}logn=%d" % (r, n))
    print("如果(X+a)^%d != X^%d+a mod {X^%d-1, %d}$输出合数" % (n, n, r, n))
    # 构造P = (X+a)^n mod (X^r-1)

    print("构造多项式(X+a)^%d,并且进行二项式展开" % n)
    X = multi_ysymbols('X')
    a = multi_ysymbols('a')
    X_a_n_expand = binomial_expand(ypolynomial1(X, a), n)
    print(X_a_n_expand)
    X.pow(r)
    reduce_poly = ypolynomial1(X, ysymbol(value=-1.0))
    print("构造消减多项式 %s" % reduce_poly)
    print("进行运算 (X+a)^%d mod (X^%d-1)" % (n, r))
    r_equ = ypolynomial_mod(X_a_n_expand, reduce_poly)
    print("得到余式: %s" % r_equ)
    print("进行运算'余式' mod %d 得到式(A)" % n)
    A = ypolynomial_reduce(r_equ, n)
    print("A = %s" % A)
    print("B = x^%d+a mod x^%d-1" % (n, r))
    B = ypolynomial1(multi_ysymbols('X', power=31), a)
    B = ypolynomial_mod(B, reduce_poly)
    print("B = %s" % B)
    C = ypolynomial_sub(A, B)
    print("C = A - B = %s" % C)
    maxa = math.floor(math.sqrt(__phi__(r)) * math.log2(n))
    print("遍历a = 1 to %d" % maxa)
    print("检查每个'%s = 0 (mod %d)'" % (C, n))
    for a in range(1, maxa + 1):
        print("检查a = %d" % a)
        C.set_variables_value(a=a)
        v = C.eval()
        if v % n != 0:
            return False

    print("步骤6 输出素数")
    return True
Exemplo n.º 27
0
 def compute_final(self, result_list, i, num_words, tag_list):
     return result_list[num_words - 1][i][0] + gmpy2.log2(self.get_transition_prob(tag_list[i]))
Exemplo n.º 28
0
 def compute_prev(self, result_list, t, i, j, word_list, tag_list):
     if t < 0:
         return gmpy2.log2(self.get_transition_prob(tag_list[i], tag_list[j])) + gmpy2.log2(self.get_emission_prob(tag_list[j], word_list[t + 1]))
     return result_list[t][i][0] + gmpy2.log2(self.get_transition_prob(tag_list[i], tag_list[j])) + gmpy2.log2(self.get_emission_prob(tag_list[j], word_list[t + 1]))
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments

    parser = argparse.ArgumentParser(description="Generate BBS parameters.")

    parser.add_argument(
        "input_file",
        help=
        """JSON file containing the seed used for generating the pseudo strong 
                                              strong prime (the name is "seed"). The required
                                              quantity of entropy it should contain depends on bitsize. As a rule of
                                              thumb the seed should contain at least 4*bitsize bits of entropy."""
    )
    parser.add_argument(
        "output_file",
        help=
        """Output JSON file where this script will write the two generated strong
                                               strong primes "p" and "q". The output file should not exist already."""
    )
    parser.add_argument(
        "min_prime_bitsize",
        type=int,
        help="minimum strong strong prime bit size (e.g. 2048).")

    args = parser.parse_args()

    # Check arguments

    output_file = args.output_file
    if os.path.exists(output_file):
        utils.exit_error("The output file '%s' already exists. Exiting." %
                         (output_file))

    # Declare a few important variables

    min_prime_bitsize = args.min_prime_bitsize

    input_file = args.input_file
    with open(input_file, "r") as f:
        data = json.load(f)
    seed = int(data["seed"])
    seed_upper_bound = int(data["seed_upper_bound"])
    approx_seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))

    utils.colprint("Minimum strong strong prime size:", str(min_prime_bitsize))
    utils.colprint("Approximate seed entropy:", str(approx_seed_entropy))

    # Precomputations

    first_primes = [2]  # List of the first primes
    PI = 2  # Product of the primes in "first_primes"
    strong_strong_integers = [
        [1]
    ]  # strong_strong_integers[i] is the list of all strong strong integers modulo
    # first_primes[i]
    number_of_strong_strong_integers = [
        1
    ]  # number_of_strong_strong_integers[i] is the number of elements of the list
    # strong_strong_integers[i]
    C = 1  # Product of the elements of "number_of_strong_strong_integers"

    while not 2**(min_prime_bitsize - 2) < PI:
        p = int(gmpy2.next_prime(first_primes[-1]))
        first_primes.append(p)
        PI *= p
        ssi = [c for c in range(p) if is_strong_strong_basis(c, p)]
        strong_strong_integers.append(ssi)
        number_of_strong_strong_integers.append(len(ssi))
        C *= len(ssi)

    utils.colprint("Number of primes considered:", str(len(first_primes)))
    utils.colprint("Number of strong strong integers to choose from:",
                   "about 2^%f" % (gmpy2.log2(C)))

    # Check that the seed is long enough

    if seed_upper_bound < C**2 * (1 << (2 * min_prime_bitsize)):
        utils.exit_error("The seed does not contain the required entropy.")

    # Precomputations for the CRT

    mu = [gmpy2.divexact(PI, p) for p in first_primes]
    delta = [gmpy2.invert(x, y) for x, y in zip(mu, first_primes)]
    gamma = [gmpy2.mul(x, y) for x, y in zip(mu, delta)]

    # Generate the first strong prime

    print("Generating the first strong strong prime...")
    (p, seed) = generate_strong_strong_prime(seed, min_prime_bitsize,
                                             strong_strong_integers,
                                             number_of_strong_strong_integers,
                                             gamma, PI)
    utils.colprint("\tThis is the first strong strong prime:", str(p))

    # Generate the second strong prime

    print("Generating the second strong strong prime...")
    (q, seed) = generate_strong_strong_prime(seed, min_prime_bitsize,
                                             strong_strong_integers,
                                             number_of_strong_strong_integers,
                                             gamma, PI)
    utils.colprint("\tThis is the second strong strong prime:", str(q))

    # Generate the BBS start

    print("Generating the BBS starting point...")
    n = p * q
    s = seed % n
    while s == 0 or s == 1 or s == p or s == q:
        s = (s + 1) % n
    s0 = (s**2) % n
    utils.colprint("\tThis is the starting point s0 of BBS:", str(s0))

    # Save p,q, and s to the output_file

    print("Saving p,q, and s0 to %s" % (output_file))
    with open(output_file, "w") as f:
        json.dump({
            "bbs_p": int(p),
            "bbs_q": int(q),
            "bbs_s": int(s0)
        },
                  f,
                  sort_keys=True)
Exemplo n.º 30
0
def integer_log2(i: Integer) -> int:
    return int(log2(i.value))
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments

    parser = argparse.ArgumentParser(
        description=
        "From a table of draws, output a seed of appropriate length.")

    parser.add_argument("input_draw_file", help="""Text file with draws.""")
    parser.add_argument(
        "output_seed_file",
        help=
        """JSON file where we can store the seed computed from the draws.""")
    parser.add_argument(
        "entropy_to_gather",
        help="""Minimum entropy to extract before drawing lone bits.""")
    parser.add_argument("--nbr_lone_bits",
                        type=int,
                        help="""Number of lone bits to extract.""",
                        default=0)

    args = parser.parse_args()

    # Check arguments

    output_seed_file = args.output_seed_file
    if os.path.exists(output_seed_file):
        utils.exit_error("The output file '%s' already exists. Exiting." %
                         (output_seed_file))

    # Declare a few important variables

    two_pow_entropy_to_gather = (1 << int(args.entropy_to_gather))

    seed = 0
    L = 1  # before lone bits are drawn, seed lies in [0,L - 1]

    lone_bits_part = 0
    nbr_lone_bits = args.nbr_lone_bits

    # Scan the input file, construct the seed

    with open(args.input_draw_file, "r") as f:

        for line in f:

            if not line or line.strip() == "" or line.startswith("#"):
                continue

            (draw_id, m, n, draw) = re.split("\s+", line.strip(), maxsplit=3)

            if draw == "None":
                continue

            m = int(m)
            n = int(n)
            draw = [int(x) for x in draw.split(",")]
            index = index_from_draw(draw, m)

            if L < two_pow_entropy_to_gather:

                print("Draw %s used to extract entropy" % (draw_id))
                seed = gmpy2.bincoef(n, m) * seed + index
                L *= gmpy2.bincoef(n, m)

            else:

                print("Draw %s used to extract a lone bit" % (draw_id))
                b = index & 1
                seed += L * (b << (args.nbr_lone_bits - nbr_lone_bits))
                nbr_lone_bits -= 1

            if L >= two_pow_entropy_to_gather and nbr_lone_bits == 0:
                break

    if nbr_lone_bits > 0 or L < two_pow_entropy_to_gather:
        utils.exit_error(
            "There wasn't enough draws to collect to request quantity of entropy and lone bits."
        )

    seed_upper_bound = L * 2**(args.nbr_lone_bits)
    seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))
    print(
        "The seed contains more than %d bits of entropy (including the %s lone bits)."
        % (seed_entropy, args.nbr_lone_bits))
    print("The seed is %d" % (seed))

    print("Saving the seed to %s" % (output_seed_file))
    with open(output_seed_file, "w") as f:
        json.dump(
            {
                "seed": int(seed),
                "seed_upper_bound": int(seed_upper_bound),
                "approx_seed_entropy": int(seed_entropy),
                "lone_bits": int(args.nbr_lone_bits)
            },
            f,
            sort_keys=True)
Exemplo n.º 32
0
dEX = cuda.to_device(np_str, stream)
dHH = cuda.device_array(np_str.shape[0], dtype=np.uint64)
dRR = cuda.device_array(10, dtype=np.int32)

r_str = np_str[rdrand.rand32() % np_str.shape[0]]
h_str = c_hash0(r_str)

set_dim(np_str.shape[0])
stream.synchronize()

hash0_kernel[DIM](dEX, dHH)

search_kernel[DIM](dHH, h_str, dRR)

np_res = dRR.copy_to_host()

v1 = gmpy2.mpz(int.from_bytes(bytes(np_str[np_res[1]]), 'big'))
v2 = gmpy2.mpz(int.from_bytes(bytes(r_str), 'big'))

assert (v1 == v2)
print(
    "Total GPU (64bit hash) search results:\t{0:,d} of {1:,d}\t(index {2:d})".
    format(np_res[0], np_str.shape[0], np_res[1]))
print("\t\t###\trdrand.seed_bytes({:d})\t###".format(SEED))
print("{0}\tlength {1:d}".format(v1.digits(2), v1.bit_length()))
print("int\t{0:d}\t(log2 ~ {1:.9f})".format(v1, gmpy2.log2(v1)))

assert (np.unique(np_str, axis=0).shape[0] == np_str.shape[0])
np_h = dHH.copy_to_host()
assert (np.unique(np_h).shape[0] == np_h.shape[0])
Exemplo n.º 33
0
 def __init__(self, n):
     self.n = n
     self.n_sq = n * n
     self.g = n + 1
     self.bits = mpz(rint_round(log2(self.n)))
Exemplo n.º 34
0
def _get_max_prime(start, gap, max_prime):
    if max_prime is None or max_prime <= 1:
        log2 = float(gmpy2.log2(start + gap))
        max_prime = verify.sieve_limit(log2, gap)
    return max_prime
Exemplo n.º 35
0
#!/usr/bin/python2
import sys
import multiprocessing
import gmpy2
import scipy
import scipy.interpolate
import numpy
import random
import itertools
import time

gmpy2.get_context().precision = 256

LOG2E = int(gmpy2.log2(gmpy2.exp(1))*2**64)

def fxp_ilog2(x):
    y = x >> 64
    lo = 0
    hi = 191
    mid = (lo + hi) >> 1
    while lo < hi:
        if (1 << mid) > y:
            hi = mid - 1
        else:
            lo = mid + 1
        mid = (lo + hi) >> 1
    return lo

def fxp_lagrange(x, coeffs):
    result = 0
    xpow = 1 << 64
Exemplo n.º 36
0
def random_from_interval(random_state, low, high, m=32):
    M = int(g.ceil(g.log2(high)))
    random = g.mpz_urandomb(random_state, M + m)
    c = g.add(g.f_mod(random, g.add(g.sub(high, low), 1)), low)
    return c
Exemplo n.º 37
0
from SecMult_Sub import Sub
from Client_Server import *
import timeit
import time
import numpy as np
from sympy.polys.domains import ZZ
from sympy.polys.galoistools import gf_neg
from sympy.polys.galoistools import *
from sympy import *
import gmpy2
from gmpy2 import mpz, mpfr, log2
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
a = 12345678901234567890
gmpy2.get_context().precision = 70
mpz(2**log2(a))
mpz(12345678901234567890)
N = 999999999999999999999999999999999999999999999999999999999999
M1 = 10000000000000000000000000000000000000000
Prec = 100000000000000000000
In_Pre = 1000000000000000
Lambda = 1000000000000000000000000000000


def mod(x, modulus):
    numer, denom = x.as_numer_denom()
    return numer * mod_inverse(denom, modulus) % modulus


def Test():
Exemplo n.º 38
0
 def __init__(self, n):
     self.n = n
     self.n_sq = n * n
     self.g = n + 1
     self.bits=mpz(rint_round(log2(self.n)))
Exemplo n.º 39
0
#import matplotlib.pyplot as plt
import os
import bisect
from numpy import linspace
# gmpy2 precision initialization
BITS = (1 << 10)
BYTES = BITS/8
gmpy2.get_context().precision = BITS # a whole lotta bits

def random():
    seed = int(os.urandom(BYTES).encode('hex'), 16)
    return gmpy2.mpfr_random(gmpy2.random_state(seed))

# Useful constants as mpfr
PI = gmpy2.acos(-1)
LOG2E = gmpy2.log2(gmpy2.exp(1))
LN2 = gmpy2.log(2)
# Same, as 192.64 fixedpoint
FX_PI = int(PI * 2**64)
FX_LOG2E = int(LOG2E * 2**64)
FX_LN2 = int(LN2 * 2**64)
FX_ONE = 1 << 64
## The index of a poly is the power of x,
## the val at the index is the coefficient.
##
## An nth degree poly is a list of len n + 1.
##
## The vals in a poly must all be floating point
## numbers.

def poly_add(p1, p2):
Exemplo n.º 40
0
                b0c = [gmpy2.mul(b, ci) for b, ci in zip(b0, c)]
                b1c = [gmpy2.mul(b, ci) for b, ci in zip(b1, c)]

                s_0b = gmpy2.mpz(0)
                s_1b = gmpy2.mpz(0)
                for j in range(n):
                    if a[j] != 0:
                        s_0b = gmpy2.add(s_0b, b0a[j])
                        s_1b = gmpy2.add(s_1b, b1a[j])
                    else:
                        s_0b = gmpy2.add(s_0b, b0c[j])
                        s_1b = gmpy2.add(s_1b, b1c[j])

                diff0 = gmpy2.sub(Ep, s_0b)
                overflow0 = gmpy2.log2(diff0)
                diff1 = gmpy2.sub(Ep, s_1b)
                overflow1 = gmpy2.log2(diff1)
                s_0b = gmpy2.digits(s_0b)
                s_1b = gmpy2.digits(s_1b)

                #print("\na: " + str(a))
                #print("b0: " + str(b0))
                #print("b1: " + str(b1))
                #print("choice: " + str(choice))
                #print("s_Ep: " + s_Ep)
                #print("s_0b: " + s_0b)
                #print("s_1b: " + s_1b)

                guess = eq_digits(no_digits, s_Ep, s_1b)