Generating RSA Key Pair in Python

  • Share this:

Code introduction


This function generates an RSA key pair using the cryptography library, including the private and public keys.


Technology Stack : cryptography library, RSA algorithm, key generation

Code Type : Generate RSA key pair

Code Difficulty : Intermediate


                
                    
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_rsa_keypair(bits=2048):
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend()
    )
    public_key = private_key.public_key()
    
    return private_key, public_key