python – Generating RSA key pairs with pycryptodome module

Thank you for the creator of pycryptodome module, this module has made RSA key pair easy.

This recipe presents a function for generating private and public key pair.

from Crypto.PublicKey import RSA  # pycryptodome


def rsa_key_gen(bits=2048, privatekey_path=RSA_PRIVATE_KEY, pubkey_path=RSA_PUBLIC_KEY):
    private_key = RSA.generate(bits)
    with open(privatekey_path, "wb") as privkey_file:
        privkey_file.write(private_key.export_key())
    with open(pubkey_path, "wb") as pubkey_file:
        pubkey_file.write(private_key.publickey().export_key())
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s