def primality_test(n, certainty=50000 ): #returns true if n is prime, if composite returns false if not isinstance(n, int): raise ValueError("n cannot be anything but an int you gave: " + str(type(n))) elif n < 1: raise ValueError("n cannot be less than 0") elif n == 1: return True elif n % 2 == 0: return False else: for i in range(0, certainty): a = random.randint(2, n - 1) if eea(a, n).get("gcd") != 1: return False k = 1 q = (n - 1) / 2 while q % 2 == 0: k = k + 1 q = q / 2 a = fast_power(a, q, n) if a == 1: continue while k > 1: if a == -1: break a = (a * a) % n k = k - 1 if a == -1: continue return True
def set_e(self, e): if self.q is None or self.p is None: raise ValueError("(self.) p and q cannot be None") if eea(e, (self.p-1)*(self.q-1)).get("gcd") == 1: self.e = e else: raise ValueError("Invalid e value, gcd of input e and (p-1)*(q-1) must be 1")
def pollard(N): a = 2 p = None for j in range(2, 1000): a = fast_power(a, j, N) d = eea(a-1, N).get("gcd") if d > 1 and d < N: p = d break return p
def test_eea_2(self): x = 63451367846845 y = 52352467468873425 self.assertEqual(eea(x, y), { "gcd": 5, "a": 4310308599955094, "x": x, "b": -5224108618601, "y": y })
def gen_e(self, p = None, q = None): if (p is not None): self.p = p if (q is not None): self.q = q e = 0 while (e != 0 and eea(e, (self.p-1)*(self.q-1)).get("gcd") != 1): e = random.randint(3, (p-1)*(q-1)) self.e = e return e
def decrypt(self, c, p = None, q = None, e = None): if q is not None and p is not None: self.q = q self.p = p self. N = self.p * self.q if e is not None: self.e = e self.c = c if None in [self.N, self.p, self.q, self.e, self.c]: raise ValueError("c, e, p, q, or N is None") g = eea(self.p - 1, self.q-1).get("gcd") self.d = int(mod_inv(self.e % ((self.p-1)*(self.q-1)/g), (self.p-1)*(self.q-1)/g)) self.m = fast_power(self.c, self.d, self.N) return self.m
def mod_inv(a, m): # Where a*b = 1 mod(m) inv = None if m <= 0: # Error and Base Case Handling raise ValueError("m cannot be 0 or less") elif a > m: raise ValueError("a cannot be larger than m") elif a == 0: return 0 else: eea_res = eea(a, m) inv = eea_res.get("a") if eea_res["gcd"] != 1: if eea_res["gcd"] != m: raise ValueError("a divides m, there is no modular inverse for a:" + str(a)+" with modulo m: "+str(m)) inv = (inv % m) return inv
def test_eea_1(self): print("\n\nRunning test for src module: eea") x = 3 y = 21 self.assertEqual(eea(x, y), {"gcd": 3, "a": 1, "x": x, "b": 0, "y": y})