Facebook
From ui, 1 Year ago, written in Plain Text.
This paste is a reply to Re: ratul from eety - view diff
Embed
Download Paste or View Raw
Hits: 218
  1. def save_key_to_file(key, filename):
  2.     # Check if the key is a private key
  3.     if isinstance(key, rsa.RSAPrivateKey):
  4.         # Serialize the private key in PEM format with PKCS8
  5.         pem = key.private_bytes(
  6.             encoding=serialization.Encoding.PEM,
  7.             format=serialization.PrivateFormat.PKCS8,
  8.             encryption_algorithm=serialization.NoEncryption()
  9.         )
  10.     else:
  11.         # Serialize the public key in PEM format
  12.         pem = key.public_bytes(
  13.             encoding=serialization.Encoding.PEM,
  14.             format=serialization.PublicFormat.SubjectPublicKeyInfo
  15.         )
  16.  
  17.     # Write the serialized key to a file using binary. use [.pem] file extension
  18.     with open(filename, 'wb') as file:
  19.       file.write(pem)
  20.  
  21.  
  22. def load_private_key_from_file(filename):
  23.     # read the saved pem file in the pem variable
  24.     with open(filename, 'wb') as file:
  25.       pem = file.read()
  26.     ## line 1
  27.         ## line 2
  28.     private_key = serialization.load_pem_private_key(
  29.         pem,
  30.         password=None,
  31.         backend=default_backend()
  32.     )
  33.     return private_key
  34.  
  35. def load_public_key_from_file(filename):
  36.     # read the saved pem file in the pem variable
  37.     with open(filename, 'wb') as file:
  38.       pem = file.read()
  39.     ## line 1
  40.         ## line 2
  41.     public_key = serialization.load_pem_public_key(
  42.         pem,
  43.         backend=default_backend()
  44.     )
  45.     return public_key
  46.  
  47. private_key, public_key = generate_keys()
  48. save_key_to_file(private_key,"private_rsa.pem")
  49. save_key_to_file(public_key,"public_rsa.pem")
  50.