RSA Keypair Generation Function

  • Share this:

Code introduction


This code defines a function that generates an RSA keypair with a specified number of bits. It first generates the private key, then generates the public key from the private key. Finally, it serializes the private and public keys to PEM format.


Technology Stack : cryptography, RSA keypair generation, serialization to PEM format

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def generate_random_keypair(bits=2048):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.primitives import serialization

    # Generate a random RSA keypair with a specified number of bits
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend()
    )
    public_key = private_key.public_key()

    # Serialize the private and public keys to PEM format
    pem_private_key = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    pem_public_key = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )

    return pem_private_key, pem_public_key