def miller_rabin(n, k=128): # compute (s, r) such that r is odd, (2^r)s = n - 1 (s, r) = (0, n - 1) while r & 1 == 0: s += 1 r //= 2 # track probability of false result, k # probability is at most 2^(-k) # loop until this probability is small enough for our security goal for _ in range(k): # choose random a such that 2 <= a <= n - 1 a = randrange(2, n - 1) # expensive operation: modular exponentiation x = modexp(a, r, n) # when x = 1, test passes for basis a if x != 1 and x != (n - 1): # the sequence x, x^2, ..., x^(2^r) must finish on value 1 # and furthermore the last value not equal to 1 must be n - 1 if n prime i = 1 while i < s and x != (n - 1): x = modexp(x, 2, n) if x == 1: return False i += 1 if x != (n - 1): return False # n has passed the primality test for basis a; # we have reduced the probability of a false result by 2^2 return True
def rsa(m: int): p = gen_prime(1024) q = gen_prime(1024) n = p * q t = totient(p, q) t_bits = int(math.floor(math.log2(t))) print("t_bits", t_bits) e = 3 # TODO: we should loop until this is true assert gcd(t, e) == 1 d = fast_multiplicative_inverse(e, t) assert d * e % t == 1 print('t', t) print('e', e) print('d', d) encrypted = modexp(m, n, e) print('enc', encrypted) decrypted = modexp(encrypted, n, d) print('dec', decrypted) key = RSA.construct((n, e, d)) export_key = key.exportKey() with open("mykey", "wb") as f: f.write(export_key)
def rcv_msg1(self, email, A): self.A = A part1 = A * modexp(self.v, self.u, self.N) S = modexp(part1, self.b, self.N) sha = hashlib.sha256() sha.update(hex(S)) self.K = sha.digest() print 'Simple server K', self.K.encode('hex') return self.salt, self.B, self.u
def rcv_msg1(self, email, A): self.client_email = email self.client_A = A B = (self.k * self.v + modexp(self.g, self.b, self.N)) % self.N self.u = compute_u(A, B) part1 = (A * modexp(self.v, self.u, self.N)) % N S = modexp(part1, self.b, self.N) sha = hashlib.sha256() sha.update(hex(S)) self.K = sha.digest() print 'Server S =', S, 'Server K = ', self.K return self.salt, B
def __init__(self, email, password, N=N, g=2): self.N = N self.g = g self.email = email self.password = password self.b = random.randint(0, N) self.salt = random.randint(0, 2**32-1) self.B = modexp(g, self.b, self.N) x = compute_x_simple(self.salt, self.password) print 'Server x', x self.v = modexp(g, x, self.N) self.u = random.randint(0, 2**128-1)
def rcv_msg2(self, salt, B): self.u = compute_u(self.A, B) sha = hashlib.sha256() sha.update(hex(salt)) sha.update(self.password) x = compute_x(salt, self.password) part1 = (B - self.k * modexp(self.g, x, self.N)) % self.N S = modexp(part1, self.a + self.u * x, self.N) sha = hashlib.sha256() sha.update(hex(S)) self.K = sha.digest() mac = hmac.new(self.K, hex(salt), hashlib.sha256).digest() return mac
def brute_force_srp(self, target): with open('/usr/share/dict/words') as words: count = 0 start = time.time() for w in words: w = w.strip() if count > 0 and count % 1000 == 0: print 'Tried', count, 'words so far', '(' + str(time.time() - start) + ') s per 1000' print 'Current word', w start = time.time() count += 1 sha1 = hashlib.sha256() sha1.update(hex(self.salt)) sha1.update(w) x = compute_x_simple(self.salt, w) S = (self.A * modexp(self.g, x, N)) % N sha2 = hashlib.sha256() sha2.update(hex(S)) K = sha2.digest() mac = hmac.new(K, hex(self.salt), hashlib.sha256).digest() if mac == target: return w raise Exception('No solution found')
def decode_cmd(key, em_len: int) -> bytes: fn = sys.argv.pop(0) data = open(fn, "rb").read() s = pkcs15.os2ip(data) m = util.modexp(s, key.n, key.e) d = pkcs15.i2osp(m, em_len) return d
def b(): print("b: started") p, g, other_public = yield [] private = dh_secret(p) public = modexp(g, p, private) secret = modexp(other_public, p, private) key = derive_key(secret) print("b: key", binascii.hexlify(key)) ct, iv = yield [public] pt = decrypt(b"b", key, iv, ct) print("b: got pt", pt) new_ct, new_iv = encrypt(b"b", key, pt + b" echo") yield [new_ct, new_iv]
def mitm_ab(self): p, g, pub_a = yield [] self.p = p self.g = g self.private = dh_secret(self.p) self.public = modexp(self.g, self.p, self.private) ct, iv = yield [p, g, self.public] secret = modexp(pub_a, self.p, self.private) self.key_a = derive_key(secret) print("ab: key_a", binascii.hexlify(self.key_a)) pt = decrypt(b"ab", self.key_a, iv, ct) new_ct, new_iv = encrypt(b"ab", self.key_b, pt) yield [new_ct, new_iv]
def __init__(self, email, password, N=N, g=2, k=3): self.N = N self.g = g self.k = k self.email = email self.password = password self.a = random.randint(0, N) self.A = modexp(self.g, self.a, self.N)
def mitm_ba(self): pub_b, *_ = yield [] secret = modexp(pub_b, self.p, self.private) self.key_b = derive_key(secret) print("ba: key", binascii.hexlify(self.key_b)) ct, iv = yield [self.public] pt = decrypt(b"ba'", self.key_b, iv, ct) new_ct, new_iv = encrypt(b"ba", self.key_a, pt) yield [new_ct, new_iv]
def get_signatures(self, message, reputation, gen_powered): signature_list = list() pseudonym_list = list() for i in range(reputation): signature_list.append( util.elgamalsign(message, self.wallets[i]['private_key'], gen_powered, P)) pseudonym_list.append( util.modexp(gen_powered, self.wallets[i]['private_key'], P)) return (signature_list, pseudonym_list)
def __init__(self, email, password, N=N, g=2): self.N = N self.g = g self.email = email self.password = password self.a = random.randint(0, N) self.A = modexp(self.g, self.a, self.N) print 'The real password is', self.password
def a(): print("a: started") start = yield [] assert start is Start p = gen_prime(256) g = 37 private = dh_secret(p) public = modexp(g, p, private) other_public, *_ = yield [p, g, public] secret = modexp(other_public, p, private) key = derive_key(secret) print("a: key", binascii.hexlify(key)) ct, iv = encrypt(b"a", key, MSG) reply_data, reply_iv = yield [ct, iv] reply_pt = decrypt(b"a", key, reply_iv, reply_data) assert reply_pt == MSG + b" echo" print("a: reply", reply_pt)
def __init__(self, email, password, N=N, g=2, k=3): self.N = N self.g = g self.k = k self.email = email self.password = password self.b = random.randint(0, N) self.salt = random.randint(0, 2**32-1) x = compute_x(self.salt, password) v = modexp(g, x, N) self.v = v
def main(): server = Server("test/fixtures/server_key") client = Client(server) assert server.decrypt(client.em) is None s = random.randint(2, server.pub_key.n) t = util.modexp(s, server.pub_key.n, server.pub_key.e) c_prime = t * client.em % server.pub_key.n p_prime = server.decrypt(c_prime) inv = fast_multiplicative_inverse(s, server.pub_key.n) msg = p_prime * inv % server.pub_key.n assert msg == client._msg assert msg < 1000000
def verify_unsafe(key, em_len: int, sig: bytes, msg: bytes) -> Tuple[bool, Dict]: """Returns true if signature is correctly verified""" s = os2ip(sig) m = modexp(s, key.n, key.e) d = i2osp(m, em_len) d = decode_pkcs_padding_unsafe(d) d = check_sha256_header(d) sig1 = sha256(msg).hexdigest() sig2 = binascii.hexlify(d).decode() return sig1 == sig2, dict( sig1=sig1, sig2=sig2, )
def rcv_msg2(self, salt, B, u): self.salt = salt self.B = B self.u = u x = compute_x_simple(salt, self.password) print 'Simple client salt, password, x', self.salt, self.password, x S = modexp(B, self.a + u * x, self.N) # This should be g**(a+x) == g**a * g**x == A * g**x print 'Simple client S', S sha = hashlib.sha256() sha.update(hex(S)) self.K = sha.digest() print 'Simple client K', self.K.encode('hex') mac = hmac.new(self.K, hex(salt), hashlib.sha256).digest() return mac
def forge_signature(key, content: bytes, ff_len: int = 6): assert getattr(key, 'd', None) is None assert key.e == 3 key_byte_len = util.get_key_length_in_bytes(key) debug(key_byte_len) digest = sha256(content).digest() msg = b'\x00' + b'\x01' + b'\xff' * ff_len + b'\x00' + SHA256_HEADER + digest pad_len = key_byte_len - len(msg) padded = (msg + b'\x00' * pad_len) n = os2ip(padded) signature = icbrt(n) + 1 debug(n, end="\n\n") res = modexp(signature, key.n, key.e) # res = nxt ** 3 assert res < key.n debug(res, end="\n\n") debug(signature, end="\n\n") forgery = binascii.hexlify(i2osp(res, key_byte_len)) desired = binascii.hexlify(i2osp(n, key_byte_len)) debug(desired, end="\n\n") debug(forgery, end="\n\n") msg_len_hex = len(msg) * 2 assert desired[:msg_len_hex] == forgery[:msg_len_hex] return i2osp(signature, key_byte_len)
def decrypt(self, msg: int) -> Optional[int]: if msg in self.data: return None self.data.add(msg) return util.modexp(msg, self._priv_key.n, self._priv_key.d)
def encrypt(self, msg: int) -> int: return util.modexp(msg, self._pub_key.n, self._pub_key.e)
def rsasp1(n, d, m): return modexp(m, n, d)
def rsa_func(b, e, N): return modexp(b, e, N)
def mod(base: int, exponent: int) -> int: return modexp(base, P, exponent)
def _encrypt_num(self, num): c = modexp(num, self.pubkey[0], self.pubkey[1]) return c
def verify_nym(self, wallet, nym, gen_powered): return util.modexp(gen_powered, wallet['private_key'], P) == nym
def _decrypt_num(self, num): return modexp(num, self.privkey[0], self.privkey[1])