import base64
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
def get_cipher(key_length):
# 生成伪随机数
r_gen = Random.new().read
# 生成密钥对象实例, 可以指定长度
rsa = RSA.generate(key_length, r_gen)
# 获取私钥
private_key = rsa.export_key()
with open('private.pem', 'wb') as f:
f.write(private_key)
# 获取公钥
public_key = rsa.public_key().export_key()
with open('public.pem', 'wb') as f:
f.write(public_key)
def encrypted_info(public_keu_path, msg):
# 读取公钥文件
key = open(public_keu_path).read()
public_key = RSA.import_key(key)
# 进行加密,加密之前先进行编码
pk = PKCS1_v1_5.new(public_key)
encode_msg = pk.encrypt(msg.encode())
# 加密之后要通过base64编码
cipher_msg = base64.b64encode(encode_msg)
return cipher_msg
def decrypt_info(private_key_path, msg):
# 先进行base64解码
decode_msg = base64.b64decode(msg)
# 获取私钥
key = open(private_key_path).read()
private_key = RSA.import_key(key)
# 进行解密
pk = PKCS1_v1_5.new(private_key)
decrypt_msg = pk.decrypt(decode_msg, 'DecryptError')
# 对解密信息进行解码
return decrypt_msg.decode()
if name == 'main':
public_key_path = 'public.pem'
private_key_path = 'private.pem'
msg = "你好周杰伦"
encode_msg = encrypted_info(public_key_path, msg)
print(encode_msg)
print("------------------------------------------")
decode_info = decrypt_info(private_key_path, encode_msg)
print(decode_info)