Generating RSA Key Pair

  • Share this:

Code introduction


This function generates a pair of RSA keys, including a private key and a public key.


Technology Stack : cryptography

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key

def generate_rsa_keys():
    # Generate an RSA private key
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    # Generate a corresponding RSA public key
    public_key = private_key.public_key()
    return private_key, public_key                
              
Tags: