rsa加解密
import rsa # rsa加密 def rsaEncrypt(str): # 生成公钥、私钥 (pubkey, privkey) = rsa.newkeys(512) print("公钥: %s 私钥: :%s" % (pubkey, privkey)) # 明文编码格式 content = str.encode("utf-8") # 公钥加密 crypto = rsa.encrypt(content, pubkey) return (crypto, privkey) # rsa解密 def rsaDecrypt(str, pk): # 私钥解密 content = rsa.decrypt(str, pk) con = content.decode("utf-8") return con if __name__ == "__main__": str, pk = rsaEncrypt("hello") print("加密后密文: %s" % str) content = rsaDecrypt(str, pk) print("解密后明文: %s" % content)
rsa生成和保存公私钥
import rsa f, e = rsa.newkeys(2048) # 生成公钥、私钥 e = e.save_pkcs1() # 保存为 .pem 格式 with open("e.pem", "wb") as x: # 保存私钥 x.write(e) f = f.save_pkcs1() # 保存为 .pem 格式 with open("f.pem", "wb") as x: # 保存公钥 x.write(f)
使用 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) y = Crypto.PublicKey.RSA.generate(2048, Crypto.Random.new().read) # 使用 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)