Skip to content

Instantly share code, notes, and snippets.

@ostinelli
Last active April 16, 2024 07:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ostinelli/aeebf4643b7a531c248a353cee8b9461 to your computer and use it in GitHub Desktop.
Save ostinelli/aeebf4643b7a531c248a353cee8b9461 to your computer and use it in GitHub Desktop.
RSA Private / Public key pair with openssl & Python

RSA Private / Pubic key pair

To generate a private / public RSA key pair, you can either use openssl, like so:

$ openssl genrsa -out private.pem 4096  
$ openssl rsa -in private.pem -outform PEM -pubout -out public.pem  

Or, you can use the following python script:

from cryptography.hazmat.backends import default_backend  
from cryptography.hazmat.primitives import serialization  
from cryptography.hazmat.primitives.asymmetric import rsa  
  
  
# save file helper  
def save_file(filename, content):  
   f = open(filename, "wb")  
   f.write(content) f.close()  
  
  
# generate private key & write to disk  
private_key = rsa.generate_private_key(  
    public_exponent=65537,  
    key_size=4096,  
    backend=default_backend()  
)  
pem = private_key.private_bytes(  
    encoding=serialization.Encoding.PEM,  
    format=serialization.PrivateFormat.PKCS8,  
    encryption_algorithm=serialization.NoEncryption()  
)  
save_file("private.pem", pem)  
  
# generate public key  
public_key = private_key.public_key()  
pem = public_key.public_bytes(  
    encoding=serialization.Encoding.PEM,  
    format=serialization.PublicFormat.SubjectPublicKeyInfo  
)  
save_file("public.pem", pem)  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment