猿问

python - 密码学 - 生成新的 RSA 私钥

我需要一个函数来生成一个新的 RSA 私钥,然后可以将其作为字符串存储在 Django 模型字段中。我正在使用密码学==2.1.4。


我虽然已经通过以下方式实现了这一目标:


from cryptography.hazmat.primitives import serialization

from cryptography.hazmat.primitives.asymmetric import rsa

from cryptography.hazmat.backends import default_backend


KEY_SIZE = 2048

PUBLIC_EXP = 65537

private_key = rsa.generate_private_key(

    public_exponent=PUBLIC_EXP,

    key_size=KEY_SIZE,

    backend=default_backend()

)

private_key_str = private_key.private_bytes(

    encoding=serialization.Encoding.PEM,

    format=serialization.PrivateFormat.TraditionalOpenSSL,

    encryption_algorithm=serialization.NoEncryption()

).decode()

但显然我在这里遗漏了一些东西或一些步骤(虽然我应该知道为什么......)因为private_key_str它总是具有相同的价值。


这里有什么建议吗?


小怪兽爱吃肉
浏览 213回答 1
1回答

慕沐林林

我用 cryptography==2.1.4 尝试你的代码,我发现它private_key_str不一样。我想也许你没有仔细比较这两个字符串。它们都使用 PEM 编码的 PKCS#1 结构来编码密钥,因此它们具有相似的结构。private_key1-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAspdHsnVqiY0RFYVAHcqa9AQvZC4u7gGv36wWCEUIlemJx2L71UvAbD5b/n/RPp4nw2xTIpSFguC+d4t5IaomQR7WR0aCcWda9SveNk4KyJmnHUoxZ6BBz4vBhdLWLLwZwxGsmuml60Wv5JMVEbf0lDgZqjIBMH0W5hFxa6f3AvI2L2XfLzwhfcyDMBIENx47aDFyWwfJvkIotFcLS9gYvo5KQXCdoHMbkoygF2cF+JAfSPEbHaRw0qCOIDb0pC/L8HUxyiSeGH9eu93KyweRTqoXdkWdmKLYlJHUsdv24xrUxeA3rARho2flkL/kz6AKO4NJJy+pvDCCtk8PW+HnTwIDAQABAoIBAD8587Yof5lHCf9Wd4aUjhtJyAVtnEvC6SME55/x4MJCNfcTAhlXgj5QLX2Cfu/uSiGTnjMl5caaDpSAGlhixrxTUIVXXyMK9lbKOxd6tb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