1. 拓展的欧几里得算法
from pprint import pprint
e = int(input("请输入公钥e:"))
n = int(input("请输入除数:"))
table = [('i', 'Q', 'R', 'x')]
assert n > e
table.append((0, 0, n, 0))
table.append((1, 0, e, 1))
while True:
i = len(table)
Q = table[-2][2] // table[-1][2]
R = table[-2][2] % table[-1][2]
x = table[-2][3] - Q * table[-1][3]
table.append((i, Q, R, x))
if R == 0:
print("无逆元")
break
elif R == 1:
assert x * e % n == 1
print(f"逆元为{x}")
break
pprint(table)
2. RSA密码体制
def RSA(
mode: str,
text: int or str,
**kwargs
):
text = int(text)
e, d, p, q = kwargs.values()
n = p * q
if mode == 'encoding':
print(f'当前需加密的明文为{text},公钥为({n},{d})')
return text ** e % n
elif mode == 'decoding':
print(f'当前需解密的密文为{text},私钥为({n},{e})')
return text ** d % n
else:
raise Exception('加密解密读取错误')
params = {
'e': 13,
'd': 937,
'p': 43,
'q': 59
}
RSA('encoding', '0802', **params)
RSA('decoding', '1324', **params)