所以我用下面的代码在python中生成了一个RSA密钥对
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend
class RSA():
def __init__(self, key_size=2048):
self._key_size = key_size
def generate(self):
key = rsa.generate_private_key(
backend=crypto_default_backend(),
public_exponent=65537,
key_size=self._key_size
)
private_key = key.private_bytes(
crypto_serialization.Encoding.PEM,
crypto_serialization.PrivateFormat.PKCS8,
crypto_serialization.NoEncryption())
public_key = key.public_key().public_bytes(
crypto_serialization.Encoding.OpenSSH,
crypto_serialization.PublicFormat.OpenSSH
)
return (private_key, public_key)
然后使用以下命令调用此类
import os
import time
from Crypto.Key import RSA
if not os.path.exists("./keys"):
os.mkdir("./keys")
rsa = RSA()
priv, pub = rsa.generate()
with open("./keys/priv.ppk", "a+") as priv_file:
priv_file.write(priv)
with open("./keys/pub.pub", "a+") as pub_file:
pub_file.write(pub)
else:
print("./keys exists")
time.sleep(30)
但是,我遇到的问题是它可以很好地创建密钥,但是在程序退出之前不会将它们保存到文件中,这是出于安全原因还是库问题,或者很可能是我的问题?< / p>