目录
1.依赖的基本数学算法、编码流操作
# 本代码文件名: __util.py
import math
def gcd(x, y):
""" 欧几里德算法 """
while x > 0:
x, y = y % x, x
return y
def extendGcd(a, b):
""" 扩展欧几里德算法 """
if b == 0:
return 1, 0
else:
x, y = extendGcd(b, a % b)
x, y = y, x - (a//b) * y
return x, y
def modInvElem(a:int, m):
""" 求整数a关于1模m的乘法逆元 """
if (gcd(a, m) !=1):
return -1
inva, _ = extendGcd(a, m)
inva %= m
return inva
def fastModExponent(a, m, n):
""" 快速模指数算法
@return: (a^m) mod n
"""
ans = 1
a = a % n # 若a比n大则取模简化
while m != 0:
if m & 1: ans = (ans * a) % n
m = m >> 1
a = (a * a) % n
return ans
def enCode(text):
""" 53编码 by Herk
@字符串:"abc" -> 编码流:"010203"
"""
pool = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
code = [(2-len(str(pool.index(i))))*'0'+str(pool.index(i)) for i in text]
return ''.join(code)
def deCode(code):
""" 53解码 by Herk
@编码流:"010203" -> 字符串:"abc"
"""
pool = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
text = [pool[int(code[i:i+2])%53] for i in range(0, len(code), 2)]
return ''.join(text)
def divideGroup(code, glen=10):
""" 对编码进行分组补全
@code: 待分组的编码流
@glen: 分组长度, 最后一组不足则右端补0
@return: 编码流的分组列表
"""
group = [code[i:i+glen] for i in range(0, len(code), glen)]
group[-1] = group[-1] + (glen - len(group[-1])) * '0'
return group
2.RSA 算法加解密、例题实现
# 本代码文件名: rsa.py
from Crypto.Util import number
from __util import *
class RSA():
""" RSA 加解密 """
def __init__(self, p=None, q=None, e=None):
""" 初始化公私钥
@获取p,q,e生成公私钥
@若为空则随机生成公私钥
"""
key = self.genParam(p, q, e)
print("公钥为:", key[0])
print("私钥为:", key[1])
def genParam(self, p, q, e):
""" 参数生成函数
@生成公钥, 生成私钥
"""
if (p==None or q==None):
__p = number.getPrime(10)
__q = number.getPrime(10)
phi = (__p-1) * (__q-1)
self.e = phi - 1 # e比phi小1, 两者必定互素
else:
self.e = e
__p, __q = p, q
phi = (__p-1) * (__q-1)
self.n = __p * __q
self.d = modInvElem(self.e, phi)
return [self.e, self.n], [self.d, self.n]
def cryptRSA(self, codes, flag):
""" RSA算法
@编码流A->编码流B
"""
codeB = '' # 待返回的编码流B
codelistA = divideGroup(codes, 10) # 分组长度要小于 n
if flag == 1: exponent = self.e # RSA正向算法
else: exponent = self.d # RSA逆向算法
for code in codelistA:
leng = len(code) # 传入编码流长度, return时补全不足
code = int(code)
code = fastModExponent(code, exponent, self.n)
codeB += str(code).zfill(leng) #zfill:编码流左端补0
return codeB
def encrypt(self, messagcode):
""" RSA加密算法
@mscode: 明文编码流
@return: 密文编码流
"""
return self.cryptRSA(messagcode, 1)
def decrypt(self, ciphercode):
""" RSA解密算法
@cipher: 密文编码流
@return: 明文编码流
"""
return self.cryptRSA(ciphercode, 0)
if __name__ == '__main__':
mscode = enCode("please wait for me")
cicode = "0763222127199153452800748825533895624854"
crypto = RSA(71593, 77041, 1757316971)
cilist = crypto.encrypt(mscode)
mslist = crypto.decrypt(cicode)
messag = deCode(mslist)
print("密文编码流为:", cilist)
print("明文编码流为:", mslist)
print("解密后的明文:", messag)