简体   繁体   中英

Python cryptography package RSA — save private key to DB

I want to encrypt something with RSA from python cryptography library. ( https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/ )

First think first, I have my secret msg and two types of keys(public and 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() 

Now I can encrypt msg with 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
    )
)

Great! But due to decrypt this message I need to use private_key :

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

All works fine, the only problem is -- I need to save private key to database and decrypt msg later. Cant use RSA class instance for that purposes.

Maybe Im using wrong tool or just don't know this library well, but so far I'm not found answer in documentation.

Will appreciate any help :)

You can serialize private key without encryption.

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

Store the pem_data into your database, and reload as the private key from PEM while you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM