code: def generate_and_store_rsa_key(key_size=2048, filename='rsa.key',
                                 passphrase=''):
      
      private_key = rsa.generate_private_key(public_exponent=65537,
                                             key_size=key_size,
                                             backend=default_backend())
  
      with open(filename, "wb") as keyfile:
          if passphrase:
              pem = private_key.private_bytes(
                  encoding=serialization.Encoding.PEM,
                  format=serialization.PrivateFormat.PKCS8,
                  encryption_algorithm=serialization.BestAvailableEncryption(
                      passphrase))
          else:
              pem = private_key.private_bytes(
                  encoding=serialization.Encoding.PEM,
                  format=serialization.PrivateFormat.PKCS8,
                  encryption_algorithm=serialization.NoEncryption())
          keyfile.write(pem)
          keyfile.close()
      return private_key
docs: Generate a private RSA key and store a PEM representation of it in a
      file.
  
      :param key_size: The size of the key, default 2048 bytes.
      :param filename: The name of the file to which the key should be written
      :param passphrase: If the PEM representation should be protected with a
          pass phrase.
      :return: A
          cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance