RSA非对称加密
这种方法用同一个人的公钥加密,用私钥解密
产生私钥和公钥
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64
# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成实例
rsa = RSA.generate(1024, random_generator)
print(rsa.__str__())
# print(len(rsa))
# 私钥的生成
private_pem = rsa.exportKey()
print(private_pem)
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)
第一步导库,库的安装Windows下安装 pycryptodome,linux下安装pycrypto
第二步生成证书,此处1024位
# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成实例
rsa = RSA.generate(1024, random_generator)
第三步生成私钥
private_pem = rsa.exportKey()
第四步生成公钥
public_pem = rsa.publickey().exportKey()
写入文件 是为了持久化,但是这里做测试不一定要写入
加密
def jiami(message):
rsakey=RSA.importKey(public_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(message.encode('utf-8')))
return cipher_text.decode('utf-8')
xx=jiami('哈哈')
print(xx)
加密使用 公钥
先导入公钥
再申明一个加解密的对象cipher
密文加密
cipher_text = base64.b64encode(cipher.encrypt(message.encode('utf-8')))
先 转换为utf8编码后再加密,再转换为b64编码
解密
def jiemi(enc):
enc=enc.encode('utf8')
rsakey=RSA.importKey(private_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text=cipher.decrypt(base64.b64decode(enc),'解密失败')
return text.decode('utf8')
yy=jiemi(xx)
print(yy)
这里读取到的是私钥,解密出明文的顺序可以看作是加密的反向顺序
加解密 的输出 如下
解密有个失败提示,但这个参数在函数中有的,实际运行还是报的别的错误