import os import textwrap from . import constants, typings def get_private_key_content(private_key: typings.PrivateKey) -> bytes: """ Get private key content from the provided private key, which is a string representing any of the following: - A path to a private key file. - A base64-encoded private key (single line, no headers/footers). - The private key itself (PEM format). Always returns bytes with NO trailing newline. """ private_key = private_key.strip() if not private_key: raise ValueError("Private key cannot be empty.") if private_key.startswith("-----BEGIN"): # Already PEM format return private_key.rstrip("\n ").encode("utf-8").rstrip(b"\n") elif os.path.exists(private_key): # File path with open(private_key, "rb") as f: return f.read().rstrip(b"\n ") else: # Assume it is base64-encoded and no line breaks, reconstruct PEM pem = ( constants.PRIVATE_KEY_HEADER.decode("utf-8") + "\n".join(textwrap.wrap(private_key, 64)) + constants.PRIVATE_KEY_FOOTER.decode("utf-8") ) return pem.encode("utf-8").rstrip(b"\n")