def generate_rsa_public_key(private_key: RSAPrivateKeyWithSerialization) -> RSAPublicKey: """Generate RSA public key. :param private_key: private key used for public key generation :return: RSA public key """ return private_key.public_key()
def save_rsa_private_key( private_key: RSAPrivateKeyWithSerialization, file_path: str, password: str = None, encoding: Encoding = Encoding.PEM, ) -> None: """Save the RSA private key to the given file. :param private_key: RSA private key to be saved :param file_path: path to the file, where the key will be stored :param password: password to private key; None to store without password :param encoding: encoding type, default is PEM """ if password: if isinstance(password, str): password_bytes = password.encode("utf-8") else: password_bytes = password enc = (serialization.BestAvailableEncryption( password=password_bytes) if password else serialization.NoEncryption()) pem_data = private_key.private_bytes(encoding, serialization.PrivateFormat.PKCS8, enc) with open(file_path, "wb") as f: f.write(pem_data)
def save_private_key(private_key: RSAPrivateKeyWithSerialization, file_path: str, password: bytes = None, encoding: Encoding = Encoding.PEM) -> None: """Save the RSA private key to the given file. :param private_key: RSA private key to be saved :param file_path: path to the file, where the key will be stored :param password: password to private key; None to store without password :param encoding: encoding type, default is PEM """ enc = serialization.BestAvailableEncryption( password) if password else serialization.NoEncryption() pem_data = private_key.private_bytes(encoding, serialization.PrivateFormat.PKCS8, enc) with open(file_path, 'wb') as f: f.write(pem_data)