55
66HEADER = '-----BEGIN RSA PRIVATE KEY-----'
77FOOTER = '-----END RSA PRIVATE KEY-----'
8+ PKCS8_HEADER = '-----BEGIN PRIVATE KEY-----'
9+ PKCS8_FOOTER = '-----END PRIVATE KEY-----'
10+ SUPPORTED_PRIVATE_KEY_FORMATS = (
11+ (HEADER , FOOTER ),
12+ (PKCS8_HEADER , PKCS8_FOOTER ),
13+ )
814
915
1016def make_bytes (val ):
@@ -39,13 +45,23 @@ def decode(byte_string: bytes) -> str:
3945
4046
4147def to_rsa_format (key : str ) -> str :
42- """Convert a private key to RSA format with proper newlines."""
48+ """Normalize a private key PEM string with proper newlines.
4349
44- if "\n " in key and HEADER in key and FOOTER in key :
50+ Supports both PKCS#1 (``-----BEGIN RSA PRIVATE KEY-----``) and
51+ PKCS#8 (``-----BEGIN PRIVATE KEY-----``) PEM formats, preserving
52+ the original header and footer markers.
53+ """
54+
55+ header , footer = next (
56+ ((hdr , ftr ) for hdr , ftr in SUPPORTED_PRIVATE_KEY_FORMATS if hdr in key and ftr in key ),
57+ (HEADER , FOOTER ),
58+ )
59+
60+ if "\n " in key and header in key and footer in key :
4561 return key
4662
4763 body = key .strip ()
48- body = body .replace (HEADER , "" ).replace (FOOTER , "" ).strip ()
64+ body = body .replace (header , "" ).replace (footer , "" ).strip ()
4965
5066 # Replace whitespace with newlines or chunk into 64-char lines
5167 if " " in body or "\t " in body :
@@ -54,4 +70,4 @@ def to_rsa_format(key: str) -> str:
5470 # PEM-encoded keys are typically split into lines of 64 characters as per RFC 7468 (section 2)
5571 body = '\n ' .join (body [i :i + 64 ] for i in range (0 , len (body ), 64 ))
5672
57- return f"{ HEADER } \n { body } \n { FOOTER } "
73+ return f"{ header } \n { body } \n { footer } "
0 commit comments