python操作RSA加密解密
2019-07-19 本文已影响0人
曹操python
python操作RSA加密解密
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Author:LBL
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP
def generate_key():
key = RSA.generate(1024)
private_key = key.export_key()
print(private_key)
with open('private.pem', 'wb') as f:
f.write(private_key)
public_key = key.publickey().export_key()
print(public_key)
with open('public_key.pem', 'wb') as f:
f.write(public_key)
# 实例化生成密钥对文件
# generate_key()
# 加密
def encrypt(data):
# 导入公钥
public_key = RSA.import_key(open('public_key.pem').read())
# 加密对象
cipher = PKCS1_OAEP.new(public_key)
# 加密
msg = cipher.encrypt(data)
return msg
# 解密
def decrypt(data):
# 导入私钥
private_key = RSA.import_key(open('private.pem').read())
cipher = PKCS1_OAEP.new(private_key)
res = cipher.decrypt(data)
return res
if __name__ == '__main__':
# 加密
data = '我是六六'.encode()
msg = encrypt(data)
print(msg)
# 解密
res = decrypt(msg)
print(res)
print(res.decode('utf-8'))