基于python实现rsa加密算法,并生成可执行程序 exe
import PySimpleGUI as sg
# 拓展欧几里得算法求最大公约数
def ex_gcd(a,b,arr):
if b == 0:
arr[0] = 1
arr[1] = 0
return a
r = ex_gcd(b,a%b,arr)
tmp = arr[0]
arr[0] = arr[1]
arr[1] = tmp - int(a/b)*arr[1]
return r
# 将最大公因数回代 辗转相除法回代求得模逆
def get_d(a,b):
arr = [0,0]
r = ex_gcd(a,b,arr)
if r == 1:
return int((arr[0]%b+b)%b)
else:
return -1
# 求解a^b % r 用平方乘(快速幂算法)
def fast_power(a,b):
if b == 0:
return 1
else:
ans = 1
while b > 0:
if b % 2 == 1:
ans = ans * a
a = a * a
b = b // 2
return ans
# 加密
def encrypt(m,e,n):
c = fast_power(m,e) % n
return c
# 解密
def decrypt(c,d,n):
m = fast_power(c,d) % n
return m
layout = [
[sg.T('请输入两个大的素数',size=(15)),sg.In(key='-sushu-',focus=True)],
[sg.T('请输入您的公钥',size=(15)),sg.In(key='-pk-')],
[sg.B('产生密钥'),sg.In(key='-sk-',size=(54),disabled=True)],
[sg.T('请输入明文(整数)',size=(15)),sg.In(key='-P-')],
[sg.T('加密后的密文',size=(15)),sg.In(key='-C-',disabled=True)],
[sg.T('解密输出后的明文',size=(15)),sg.In(key='-RES-',disabled=True)],
[sg.B('加密'),sg.B('解密'),sg.B('重置')]
]
window = sg.Window('RSA算法演示程序',layout)
while 1:
event, values = window.read()
# print(values)
if event == None:
break
if event == '产生密钥':
if values['-sushu-'] == '' or values['-pk-'] == '':
sg.Popup('提示', '请输入素数和私钥!', title='提示')
else:
p, q = map(int, values['-sushu-'].split())
e = int(values['-pk-'])
n = p * q
r = (p - 1) * (q - 1)
d = get_d(e, r)
window['-sk-'].update(value='公钥为{e,n}={'+str(e)+','+str(n)+'} 私钥为{d,n}={'+str(d)+','+str(n)+'}')
if event == '加密':
if values['-P-'] == '' or values['-sushu-'] == '' or values['-pk-'] == '':
sg.Popup('提示', '请自己实现加密函数!', title='提示')
else:
m = int(values['-P-'])
p, q = map(int, values['-sushu-'].split())
e = int(values['-pk-'])
n = p * q
c = encrypt(m, e, n)
window['-C-'].update(value=c)
if event == '解密':
if values['-C-'] == '':
sg.Popup('提示', '请自己实现解密函数!', title='提示')
else:
c = int(values['-C-'])
p, q = map(int, values['-sushu-'].split())
e = int(values['-pk-'])
n = p * q
r = (p - 1) * (q - 1)
d = get_d(e, r)
m = decrypt(c, d, n)
window['-RES-'].update(value=m)
if event == '重置':
for item in values:
window[item].update(value='')
window['-sushu-'].SetFocus()
window.close()
平方乘函数(快速幂)代码也可以写成(采用位运算,这样更容易理解)
# 输入(a为底数 n为指数 b为模数) 输出就是表达式的值
def fast_power(a,n,b):
ans = 1
base = a
while n != 0:
if n & 1 != 0:
ans *= base
base *= base
n >>= 1
return ans % b