Last active
January 26, 2025 21:38
-
-
Save dsbilling/a4d14b2530898865d2223959d5637355 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Requires the cryptography package from pip | |
| from cryptography.hazmat.backends import default_backend | |
| from cryptography.hazmat.primitives import serialization | |
| from cryptography.hazmat.primitives.asymmetric import rsa | |
| # Generate RSA private key | |
| private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) | |
| # Serialize private key to PEM format | |
| pem_private_key = private_key.private_bytes( | |
| encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() | |
| ) | |
| # Save private key to a file | |
| with open('private_key.pem', 'wb') as private_key_file: | |
| private_key_file.write(pem_private_key) | |
| # Generate RSA public key | |
| public_key = private_key.public_key() | |
| # Serialize public key to PEM format | |
| pem_public_key = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) | |
| # Save public key to a file | |
| with open('public_key.pem', 'wb') as public_key_file: | |
| public_key_file.write(pem_public_key) | |
| # Load and print private key | |
| with open('private_key.pem', 'rb') as private_key_file: | |
| private_key = private_key_file.read() | |
| loaded_private_key = serialization.load_pem_private_key(private_key, password=None, backend=default_backend()) | |
| # Load and print public key | |
| with open('public_key.pem', 'rb') as public_key_file: | |
| public_key = public_key_file.read() | |
| print(str(private_key)) | |
| print('-----------------') | |
| print(str(public_key)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment