写作业的时候上网查了很多篇发现有些代码并不适合,所以自己敲了个简易版...
书上定义:
书上例题:
代码部分
import random
import math
p = int(input("输入第一个素数p:"))
q = int(input("输入第二个素数q:"))
n = p * q
fn = (p-1) * (q-1)
# 求逆元
def find_mod_inverse(e, fn):
for i in range(1, fn):
if (e * i) % fn == 1: # 求e的逆元d(mod fn)
return i
return False
# 求公钥(e,n)和私钥(d,n)
e_list = []
for i in range(1, fn): # 令0<e<fn
if math.gcd(fn, i) == 1: # 令(fn,e)=1
e_list.append(i)
e = random.choice(e_list)
d = find_mod_inverse(e, fn)
print("n={},随机选取e={},此时d={}".format(n, e, d))
print("公钥:({},{}),私钥:({},{})".format(e, n, d, n))
# 加密算法
def encrypt(content):
encrypt_list = [] # 存储密文
for char in content:
m = ord(char)
c = pow(m, e, n)
encrypt_list.append(c)
return encrypt_list
# 解密算法
def decrypt(content):
decryption_content = "" # 存储解密结果
for char in content:
c = int(char)
m = chr(pow(c, d, n))
decryption_content += m
return decryption_content
# 明文
plaintext = "meet me at my office at eight o'clock"
# 密文
ciphertext = encrypt(plaintext)
print("明文为:", plaintext)
print("密文为:", ciphertext)
print("解密后:", decrypt(ciphertext))
才疏学浅,有错欢迎大家指正(●'◡'●)