如何将私钥和公钥存储到python的rsa模块生成的pem文件中
我在 python 中使用以下模块进行rsa加密。
https://github.com/sybrenstuvel/python-rsa
可以通过pip安装,如下pip3 install rsa
我已经阅读了在此处使用此模块的信息:https : //github.com/sybrenstuvel/python-rsa/blob/master/doc/usage.rst
我能够生成公钥和私钥,还能够使用以下代码使用公钥加密消息
import rsa
pubKey, priKey = rsa.newkeys(1024)
print("Public key: ",pubKey)
print("Private key: ",priKey)
msg = "vinay kumar shukla".encode('utf8')
print("Message without encryption:",msg)
msgEnc = rsa.encrypt(msg, pubKey)
print("encrypted message:",msgEnc)
但我想将私钥存储到某个文件中,正如您可以在该模块的使用文件中读取的那样,他们提供了从.pem文件中读取密钥的方法,因此这意味着我也应该将密钥存储在pem文件中,但我是不知道如何将这个模块生成的密钥存储到文件中。
当我打印此模块生成的私钥时,它给了我以下输出
PrivateKey(8647494628885176696347621451257950700244697066080136004727560667550523829374958314554596272099668415472356485265099323795859891239567212729331504592847959, 65537, 80620400968137738399200401402545247384675983145016755403642821122013062179228267902734675759971390409853232911734749752372599473758015795215587460952985, 6068766834338315918835399238932380729501892761840591316766866213831546939444337723, 1424917922362067845458877023625137340152906787710542109910805914692739733)
如果我创建一个文件key.pem并将此密钥存储到文件中,则存储此密钥。文件的内容是
-----BEGIN RSA PRIVATE KEY-----
PrivateKey(8647494628885176696347621451257950700244697066080136004727560667550523829374958314554596272099668415472356485265099323795859891239567212729331504592847959, 65537, 80620400968137738399200401402545247384675983145016755403642821122013062179228267902734675759971390409853232911734749752372599473758015795215587460952985, 6068766834338315918835399238932380729501892761840591316766866213831546939444337723, 1424917922362067845458877023625137340152906787710542109910805914692739733)
-----END RSA PRIVATE KEY-----
当我尝试阅读它时,它给了我错误,例如padding error etc请告诉我如何存储这些密钥,然后将其读取以进行解密。
回答
GitHub的网站的Python RSA通过其指的是网页此文件,根据该库有专门的方法来键导出PKCS#1格式(方法rsa. PublicKey#save_pkcs1()或rsa.PrivateKey#save_pkcs1())或将其导入(classmethodsrsa.PublicKey.load_pkcs1()或rsa.PrivateKey.load_pkcs1())。支持编码 PEM(文本)或 DER(二进制),例如:
import rsa
# Use at least 2048 bit keys nowadays, see e.g. https://www.keylength.com/en/4/
publicKey, privateKey = rsa.newkeys(2048)
# Export public key in PKCS#1 format, PEM encoded
publicKeyPkcs1PEM = publicKey.save_pkcs1().decode('utf8')
print(publicKeyPkcs1PEM)
# Export private key in PKCS#1 format, PEM encoded
privateKeyPkcs1PEM = privateKey.save_pkcs1().decode('utf8')
print(privateKeyPkcs1PEM)
# Save and load the PEM encoded keys as you like
# Import public key in PKCS#1 format, PEM encoded
publicKeyReloaded = rsa.PublicKey.load_pkcs1(publicKeyPkcs1PEM.encode('utf8'))
# Import private key in PKCS#1 format, PEM encoded
privateKeyReloaded = rsa.PrivateKey.load_pkcs1(privateKeyPkcs1PEM.encode('utf8'))
plaintext = "vinay kumar shukla".encode('utf8')
print("Plaintext: ", plaintext)
ciphertext = rsa.encrypt(plaintext, publicKeyReloaded)
print("Ciphertext: ", ciphertext)
decryptedMessage = rsa.decrypt(ciphertext, privateKeyReloaded)
print("Decrypted message: ", decryptedMessage)