Python3笔记之RSA生成公钥、私钥
简介
# python3 可以使用 Crypto.PublicKey.RSA 和 rsa 生成公钥、私钥。
# 其中 python3.6 Crypto 库的安装方式请参考连接:https://blog.csdn.net/qq_42486920/article/details/80850974
安装环境
pip3 install rsa
使用 Crypto.PublicKey.RSA 生成公钥、私钥:
import Crypto.PublicKey.RSA
import Crypto.Random
x = Crypto.PublicKey.RSA.generate(2048)
a = x.exportKey("PEM")
b = x.publickey().exportKey()
with open("a.pem", "wb") as x:
x.write(a)
with open("b.pem", "wb") as x:
x.write(b)
// 使用 Crypto.Random.new().read 伪随机数生成器
y = Crypto.PublicKey.RSA.generate(2048, Crypto.Random.new().read)
c = y.exportKey()
d = y.publickey().exportKey()
with open("c.pem", "wb") as x:
x.write(c)
with open("d.pem", "wb") as x:
x.write(d)
使用 Crypto.PublicKey.RSA.importKey(private_key) 生成公钥和证书:
import Crypto.PublicKey.RSA
with open("a.pem", "rb") as x:
xx = Crypto.PublicKey.RSA.importKey(x.read())
b = xx.publickey().exportKey()
with open("b.pem", "wb") as x:
x.write(b)
a = xx.exportKey("DER")
with open("a.der", "wb") as x:
x.write(a)
使用 rsa 生成公钥、私钥:
import rsa
f, e = rsa.newkeys(2048)
e = e.save_pkcs1()
with open("e.pem", "wb") as x:
x.write(e)
f = f.save_pkcs1()
with open("f.pem", "wb") as x:
x.write(f)
RSA非对称加密算法实现:
使用Crypto模块:
import Crypto.PublicKey.RSA
import Crypto.Cipher.PKCS1_v1_5
import Crypto.Random
import Crypto.Signature.PKCS1_v1_5
import Crypto.Hash
y = b"abcdefg1234567"
with open("b.pem", "rb") as x:
b = x.read()
cipher_public = Crypto.Cipher.PKCS1_v1_5.new(Crypto.PublicKey.RSA.importKey(b))
cipher_text = cipher_public.encrypt(y)
with open("a.pem", "rb") as x:
a = x.read()
cipher_private = Crypto.Cipher.PKCS1_v1_5.new(Crypto.PublicKey.RSA.importKey(a))
text = cipher_private.decrypt(cipher_text, Crypto.Random.new().read)
assert text == y
with open("c.pem", "rb") as x:
c = x.read()
c_rsa = Crypto.PublicKey.RSA.importKey(c)
signer = Crypto.Signature.PKCS1_v1_5.new(c_rsa)
msg_hash = Crypto.Hash.SHA256.new()
msg_hash.update(y)
sign = signer.sign(msg_hash)
with open("d.pem", "rb") as x:
d = x.read()
d_rsa = Crypto.PublicKey.RSA.importKey(d)
verifer = Crypto.Signature.PKCS1_v1_5.new(d_rsa)
msg_hash = Crypto.Hash.SHA256.new()
msg_hash.update(y)
verify = verifer.verify(msg_hash, sign)
print(verify)
// 运行结果:True
使用 rsa 模块:
import rsa
y = b"abcdefg1234567"
with open("e.pem", "rb") as x:
e = x.read()
e = rsa.PrivateKey.load_pkcs1(e)
with open("f.pem", "rb") as x:
f = x.read()
f = rsa.PublicKey.load_pkcs1(f)
cipher_text = rsa.encrypt(y, f)
text = rsa.decrypt(cipher_text, e)
assert text == y
sign = rsa.sign(y, e, "SHA-256")
verify = rsa.verify(y, sign, f)
print(verify)