from Crypto import Random from Crypto.PublicKey import RSA # 伪随机数生成器 random_gen = Random.new().read # 生成秘钥对实例对象:1024是秘钥的长度 rsa = RSA.generate(1024, random_gen) # 获取公钥,保存到文件 private_pem = rsa.exportKey() with open('private.pem', 'wb') as f: f.write(private_pem) # 获取私钥保存到文件 public_pem = rsa.publickey().exportKey() with open('public.pem', 'wb') as f: f.write(public_pem)
公钥格式:
私钥的格式:
2、加密与解密 1、公钥加密
import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 msg = "待加密明文内容" # 读取文件中的公钥 key = open('public.pem').read() publickey = RSA.importKey(key) # 进行加密 pk = PKCS1_v1_5.new(publickey) encrypt_text = pk.encrypt(msg.encode()) # 加密通过base64进行编码 result = base64.b64encode(encrypt_text) print(result)
2、私钥解密import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 # 密文 msg='bAlnUNEJeDLnWikQs1ejwqPTo4qZ7RWxgFwoO4Bfg3C7EY+1HN5UvJYJ2h6047K6vNjG+TiIxc0udTR7a12MivSA+DwoGjwFIb25u3zc+M8KTCaCT5GdSumDOto2tsKYaVDKCPZpdwYdzYwlVijr6cPcchQTlD1yfKk2khhNchU=' # base64解码 msg = base64.b64decode(msg) # 获取私钥 privatekey = open('private.pem').read() rsakey = RSA.importKey(privatekey) # 进行解密 cipher = PKCS1_v1_5.new(rsakey) text = cipher.decrypt(msg, 'DecryptError') # 解密出来的是字节码格式,decodee转换为字符串 print(text.decode())
3、分段加密和解密上面生成秘钥的时候提到过在我们加密的时候,如果数据长度超过了当前秘钥的所能处理最大长度,则需要进行分段加密,
分段加密:通俗易懂的讲就是把原来一长串的数据,分割成多段,每段的大小控制在秘钥的最大加密数量之内,加密完了之后再把数据进行拼接。 分段解密:经过分段加密的数据,在进行解密的时候我们也要将它进行分成多段,然后解密之后再进行拼接就能得到原来的数据内容。分段加密和解密的代码如下:
import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 def cipher(msg): """ 公钥加密 :param msg: 要加密内容 :return: 加密之后的密文 """ # 获取公钥 key = open('public.pem').read() publickey = RSA.importKey(key) # 分段加密 pk = PKCS1_v1_5.new(publickey) encrypt_text = [] for i in range(0,len(msg),100): cont = msg[i:i+100] encrypt_text.append(pk.encrypt(cont.encode())) # 加密完进行拼接 cipher_text = b''.join(encrypt_text) # base64进行编码 result = base64.b64encode(cipher_text) return result.decode() def decrypt(msg): """ 私钥进行解密 :param msg: 密文:字符串类型 :return: 解密之后的内容 """ # base64解码 msg = base64.b64decode(msg) # 获取私钥 privatekey = open('private.pem').read() rsakey = RSA.importKey(privatekey) cipher = PKCS1_v1_5.new(rsakey) # 进行解密 text = [] for i in range(0,len(msg),128): cont = msg[i:i+128] text.append(cipher.decrypt(cont,1)) text = b''.join(text) return text.decode()
3、签名和验签 1、私钥签名