【问题标题】:Python cryptography package RSA -- save private key to DBPython密码学包RSA——将私钥保存到数据库
【发布时间】:2023-10-29 06:28:01
【问题描述】:

我想用来自 python cryptography 库的 RSA 加密一些东西。 (https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/)

首先想一想,我有我的秘密消息和两种类型的密钥(公钥和私钥):

from cryptography.hazmat.primitives.asymmetric import rsa 

SECRET = 'Ligula Venenatis Etiam Fermentum'

private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

public_key = private_key.public_key() 

现在我可以用 public_key 加密味精了:

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

ciphertext = public_key.encrypt(
    SECERT,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

太棒了!但是由于要解密此消息,我需要使用private_key

plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA1()),
        algorithm=hashes.SHA1(),
        label=None
    )
)

一切正常,唯一的问题是 - 我需要将私钥保存到数据库并稍后解密 msg。不能为此目的使用 RSA 类实例。

也许我使用了错误的工具或者只是不太了解这个库,但到目前为止我还没有在文档中找到答案。

将不胜感激任何帮助:)

【问题讨论】:

    标签: python encryption cryptography


    【解决方案1】:

    您可以在不加密的情况下序列化私钥。

    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
    )
    pem_data = pem.splitlines()[0]
    

    将 pem_data 存储到您的数据库中,并在需要时从 PEM 作为私钥重新加载。

    【讨论】:

      最近更新 更多