GitLab system status is available here and here

Commit c3f29a62 authored by Jamie Deng's avatar Jamie Deng
Browse files

rsa.py

parents
# extended GCD algorithm
def x_gcd(a, b):
"""return (g, x, y) such that a*x + b*y = g = gcd(a, b)"""
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
(q, a), b = divmod(b, a), a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, y0
# multiplicative inverse mod n
def mod_inv(a, n):
g, x, y = x_gcd(a, n)
if g != 1:
raise ValueError('mod_inv for {} does not exist'.format(a))
return x % n
import random
def is_prime(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if n != int(n):
return False
n = int(n)
# Miller-Rabin test for prime
if n == 0 or n == 1 or n == 4 or n == 6 or n == 8 or n == 9:
return False
if n == 2 or n == 3 or n == 5 or n == 7:
return True
s = 0
d = n - 1
while d % 2 == 0:
d >>= 1
s += 1
assert (2 ** s * d == n - 1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
for i in range(8): # number of trials
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
# hw5 question 3
def q3():
n = 900348238029332668175881559281442423068410198618801978249457479037932527260331
e = 2**16 + 1
x = 39611541800605679895240898832274013906789
y = pow(x, e, n)
print('y =', y)
# hw5 question 4
def q4():
p = 929960838713976909720407931803976852619
q = 808840137850295240473898249118645909517
n = p * q
e = 2**16 + 1
print('n =', n)
phi = (p-1) * (q-1)
print('phi =', phi)
y = 159734044950403172452950888182831615189169981060911046776030041921878667289492
d = mod_inv(e, phi)
print('d =', d)
print('check d*e mod phi = 1:', d*e % phi == 1)
x = pow(y, d, n)
print('x =', x)
x_hex = hex(x)
#x_hex = x_hex[2:-1] + '0' + x_hex[-1]
#print(x_hex)
x_len = (x.bit_length()+7)//8
print("dec len", x_len)
print("hex ", x_hex)
x_bytes = x.to_bytes(x_len, 'big')
print("bytes ", x_bytes)
x_string = x_bytes.decode('ascii')
print("ascii ", x_string)
def q5():
n = 675165783015058999747250696593100898855524580839851357422716901254932757710763
e = 2**16 + 1
s = 284741839593698522184778360417494843180877037145726733862568997913589354461044
m = pow(s, e, n)
m_len = (m.bit_length()+7) // 8
m_bytes = m.to_bytes(m_len, 'big')
m_string = m_bytes.decode('ascii')
print(m_string)
def q6():
m521 = 2**521 - 1
print('is M_521 a prime:', is_prime(m521))
#q3()
#q4()
#q5()
q6()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment