我想使用 python cryptography
库中的 RSA 加密某些内容。
(https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/)
首先想一想,我有我的 secret 消息和两种类型的 key (公共(public)和私有(private)):
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
)
)
一切正常,唯一的问题是——我需要将私钥保存到数据库并稍后解密消息。无法将 RSA 类实例用于该目的。
也许我使用了错误的工具或者只是不太了解这个库,但到目前为止我还没有在文档中找到答案。
非常感谢任何帮助:)
最佳答案
您可以序列化私钥而不加密。
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 重新加载为私钥。
关于Python密码学包RSA——将私钥保存到DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36056415/