Generate RSA Keypair with Cryptography Library

  • Share this:

Code introduction


This function generates an RSA keypair using the cryptography library, including a private key and a public key. The private key is used for decryption and signing, while the public key is used for encryption and verification of signatures.


Technology Stack : Cryptography library, RSA keypair generation, private key, public key

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding

def generate_rsa_keypair():
    """
    This function generates a RSA keypair using the cryptography library.
    """
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = private_key.public_key()

    return private_key, public_key