from cryptography.hazmat.primitives import serialization def load_private_key(key, path, passphrase) -> bytes: """Load a private key from a raw PEM string or a file. Args: key: PEM private key as a plain string. When truthy, ``path`` is ignored. path: Path to a PEM key file. Used when ``key`` is falsy. passphrase: Optional passphrase to decrypt the key. Returns: DER-encoded private key bytes suitable for Snowflake JWT auth. """ if not key: with open(path, 'rb') as f: key_bytes = f.read() else: key_bytes = key.encode() p_key = serialization.load_pem_private_key( key_bytes, password=passphrase.encode() if passphrase else None, ) return p_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), )