def test_randprime(): import random random.seed(1234) assert randprime(2, 3) == 2 assert randprime(1, 3) == 2 assert randprime(3, 5) == 3 raises(ValueError, lambda: randprime(20, 22)) for a in [100, 300, 500, 250000]: for b in [100, 300, 500, 250000]: p = randprime(a, a + b) assert a <= p < (a + b) and isprime(p)
def FiatShamirGenerationKey(): # Генерируем два простых числа и вычисляем их произведение p = randprime(2 ** 139, 2 ** 140) q = randprime(2 ** 139, 2 ** 140) n = p * q # Выбираем s, взаимно-простое с mod, и вычисляем V s = random.randint(1, n) while(NOD(s, n) != 1): s = s + 1 v = pow(s, 2, n) return jsonify({"n": str(n), "s": str(s), "v": str(v)})
def generateKey(size): p = nt.randprime(2 ** (size - 1),2 ** size - 1) q = nt.randprime(2 ** (size - 1),2 ** size - 1) n = p*q phiN = (p - 1) * (q - 1) # totient # choose e # e is coprime with phiN & 1 < e <= phiN while True: e = random.randrange(2 ** (size - 1), 2 ** size - 1) if (isCoPrime(e, phiN)): break # choose d # d is mod inv of e with respect to phiN, e * d (mod phiN) = 1 d = modinv(e, phiN) return p,q,n,phiN,e,d
def GuillouQuisquaterGenerationKey(): # Вытаскиваем данные из json data = request.get_json() attr = str(data.get('attr')) # Генерируем простые p и q из диапазона p = randprime(2 ** 139, 2 ** 140) q = randprime(2 ** 139, 2 ** 140) # Вычисляем произведение n = p * q # Вычисляем функцию эйлера для n f = euler(p,q) # Вычисляем e из [1, fn], взаимно простое с fn e = random.randint(1, f) while(NOD(e, f) != 1): e = e + 1 # Вычисляем s s = bezout(e,f) att = bytes(attr, 'utf-8') hashAttr = hashlib.sha1(att) J = int(hashAttr.hexdigest(), 16) # Вычисляем закрытый ключ x и y x = pow(bezout(J, n), s, n) y = pow(x, e, n) return jsonify({"n": str(n), "e": str(e), "y": str(y), "x": str(x)})
def SchnorrGenerationKey(): # Генерируем простое число из диапазона q = randprime(2 ** 139, 2 ** 140) # Генерируем целое число rand = random.randint(2 ** 371, 2 ** 372) # Произведение testP = q * rand # Пока testP+1 не станет простым, генерируем заново и считаем произведение # в итоге получим, что простое q - делитель p - 1, а p - простое while(mr(testP + 1, [31, 72]) == False): q = randprime(2 ** 139, 2 ** 140) rand = random.randint(2 ** 371, 2 ** 372) testP = q * rand p = testP + 1 # Ищем g, мультипликативный порядок по модулю p которого равен q (g^q = (1 mod p)) h = random.randint(1, p - 1) g = pow (h, (p - 1) // q, p) while(g == 1): h = random.randint(1, p - 1) g = pow (h, (p - 1) // q, p) # Вычисляем параметры w и y w = random.randint(0, q - 1) y = pow(bezout(g, p), w, p) return jsonify({"p": str(p), "q": str(q), "g": str(g), "y": str(y), "w": str(w)})
def safe_prime(bits=512): """Generate a safe prime that is at least 'bits' bits long. The result should be greater than 1 << (bits-1). PARAMETERS ========== bits: An integer representing the number of bits in the safe prime. Must be greater than 1. RETURNS ======= An interger matching the spec. """ assert bits > 1 min = 2 ** (bits - 2) max = 2 ** (bits - 1) q = ntheory.randprime(min,max) while q <= max: p = (q * 2) + 1 if (ntheory.isprime(q) and ntheory.isprime(p)): return p q = ntheory.randprime(min,max) return 2
def test_randprime(): assert randprime(10, 1) is None assert randprime(2, 3) == 2 assert randprime(1, 3) == 2 assert randprime(3, 5) == 3 raises(ValueError, lambda: randprime(20, 22)) for a in [100, 300, 500, 250000]: for b in [100, 300, 500, 250000]: p = randprime(a, a + b) assert a <= p < (a + b) and isprime(p)
def zzx_mod_gcd(f, g, **flags): """Modular small primes polynomial GCD over Z[x]. Given univariate polynomials f and g over Z[x], returns their GCD and cofactors, i.e. polynomials h, cff and cfg such that: h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) The algorithm uses modular small primes approach. It works by computing several GF(p)[x] GCDs for a set of randomly chosen primes and uses Chinese Remainder Theorem to recover the GCD over Z[x] from its images. The algorithm is probabilistic which means it never fails, however its running time depends on the number of unlucky primes chosen for computing GF(p)[x] images. For more details on the implemented algorithm refer to: [1] J. von zur Gathen, J. Gerhard, Modern Computer Algebra, First Edition, Cambridge University Press, 1999, pp. 158 """ n = zzx_degree(f) m = zzx_degree(g) cf = zzx_content(f) cg = zzx_content(g) h = igcd(cf, cg) f = [c // h for c in f] g = [c // h for c in g] if n <= 0 or m <= 0: return zzx_strip([h]), f, g else: gcd = h A = max(zzx_abs(f) + zzx_abs(g)) b = igcd(zzx_LC(f), zzx_LC(g)) B = int(ceil(2**n * A * b * sqrt(n + 1))) k = int(ceil(2 * b * log((n + 1)**n * A**(2 * n), 2))) l = int(ceil(log(2 * B + 1, 2))) prime_max = max(int(ceil(2 * k * log(k))), 51) while True: while True: primes = set([]) unlucky = set([]) ff, gg, hh = {}, {}, {} while len(primes) < l: p = randprime(3, prime_max + 1) if (p in primes) and (b % p == 0): continue F = gf_from_int_poly(f, p) G = gf_from_int_poly(g, p) H = gf_gcd(F, G, p) primes.add(p) ff[p] = F gg[p] = G hh[p] = H e = min([gf_degree(h) for h in hh.itervalues()]) for p in set(primes): if gf_degree(hh[p]) != e: primes.remove(p) unlucky.add(p) del ff[p] del gg[p] del hh[p] if len(primes) < l // 2: continue while len(primes) < l: p = randprime(3, prime_max + 1) if (p in primes) or (p in unlucky) or (b % p == 0): continue F = gf_from_int_poly(f, p) G = gf_from_int_poly(g, p) H = gf_gcd(F, G, p) if gf_degree(H) != e: unlucky.add(p) else: primes.add(p) ff[p] = F gg[p] = G hh[p] = H break fff, ggg = {}, {} for p in primes: fff[p] = gf_quo(ff[p], hh[p], p) ggg[p] = gf_quo(gg[p], hh[p], p) F, G, H = [], [], [] crt_mm, crt_e, crt_s = crt1(primes) for i in xrange(0, e + 1): C = [b * zzx_nth(hh[p], i) for p in primes] c = crt2(primes, C, crt_mm, crt_e, crt_s, True) H.insert(0, c) H = zzx_strip(H) for i in xrange(0, zzx_degree(f) - e + 1): C = [zzx_nth(fff[p], i) for p in primes] c = crt2(primes, C, crt_mm, crt_e, crt_s, True) F.insert(0, c) for i in xrange(0, zzx_degree(g) - e + 1): C = [zzx_nth(ggg[p], i) for p in primes] c = crt2(primes, C, crt_mm, crt_e, crt_s, True) G.insert(0, c) H_norm = zzx_l1_norm(H) F_norm = zzx_l1_norm(F) G_norm = zzx_l1_norm(G) if H_norm * F_norm <= B and H_norm * G_norm <= B: break return zzx_mul_term(H, gcd, 0), F, G
def private_key(limit): return randprime(2, limit)
def zzx_mod_gcd(f, g, **flags): """Modular small primes polynomial GCD over Z[x]. Given univariate polynomials f and g over Z[x], returns their GCD and cofactors, i.e. polynomials h, cff and cfg such that: h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) The algorithm uses modular small primes approach. It works by computing several GF(p)[x] GCDs for a set of randomly chosen primes and uses Chinese Remainder Theorem to recover the GCD over Z[x] from its images. The algorithm is probabilistic which means it never fails, however its running time depends on the number of unlucky primes chosen for computing GF(p)[x] images. For more details on the implemented algorithm refer to: [1] J. von zur Gathen, J. Gerhard, Modern Computer Algebra, First Edition, Cambridge University Press, 1999, pp. 158 """ n = zzx_degree(f) m = zzx_degree(g) cf = zzx_content(f) cg = zzx_content(g) h = igcd(cf, cg) f = [ c // h for c in f ] g = [ c // h for c in g ] if n <= 0 or m <= 0: return zzx_strip([h]), f, g else: gcd = h A = max(zzx_abs(f) + zzx_abs(g)) b = igcd(zzx_LC(f), zzx_LC(g)) B = int(ceil(2**n*A*b*sqrt(n + 1))) k = int(ceil(2*b*log((n + 1)**n*A**(2*n), 2))) l = int(ceil(log(2*B + 1, 2))) prime_max = max(int(ceil(2*k*log(k))), 51) while True: while True: primes = set([]) unlucky = set([]) ff, gg, hh = {}, {}, {} while len(primes) < l: p = randprime(3, prime_max+1) if (p in primes) and (b % p == 0): continue F = gf_from_int_poly(f, p) G = gf_from_int_poly(g, p) H = gf_gcd(F, G, p) primes.add(p) ff[p] = F gg[p] = G hh[p] = H e = min([ gf_degree(h) for h in hh.itervalues() ]) for p in set(primes): if gf_degree(hh[p]) != e: primes.remove(p) unlucky.add(p) del ff[p] del gg[p] del hh[p] if len(primes) < l // 2: continue while len(primes) < l: p = randprime(3, prime_max+1) if (p in primes) or (p in unlucky) or (b % p == 0): continue F = gf_from_int_poly(f, p) G = gf_from_int_poly(g, p) H = gf_gcd(F, G, p) if gf_degree(H) != e: unlucky.add(p) else: primes.add(p) ff[p] = F gg[p] = G hh[p] = H break fff, ggg = {}, {} for p in primes: fff[p] = gf_quo(ff[p], hh[p], p) ggg[p] = gf_quo(gg[p], hh[p], p) F, G, H = [], [], [] crt_mm, crt_e, crt_s = crt1(primes) for i in xrange(0, e + 1): C = [ b * zzx_nth(hh[p], i) for p in primes ] c = crt2(primes, C, crt_mm, crt_e, crt_s, True) H.insert(0, c) H = zzx_strip(H) for i in xrange(0, zzx_degree(f) - e + 1): C = [ zzx_nth(fff[p], i) for p in primes ] c = crt2(primes, C, crt_mm, crt_e, crt_s, True) F.insert(0, c) for i in xrange(0, zzx_degree(g) - e + 1): C = [ zzx_nth(ggg[p], i) for p in primes ] c = crt2(primes, C, crt_mm, crt_e, crt_s, True) G.insert(0, c) H_norm = zzx_l1_norm(H) F_norm = zzx_l1_norm(F) G_norm = zzx_l1_norm(G) if H_norm*F_norm <= B and H_norm*G_norm <= B: break return zzx_mul_term(H, gcd, 0), F, G
def generateLargePrime(keysize): """ return random large prime number of keysize bits in size """ return nt.randprime(2**(keysize - 1), 2**keysize - 1)
def build_random_prime_from_interval(lower_value, higher_value): return nt.randprime(lower_value, higher_value)