Last active
May 22, 2025 16:39
-
-
Save imjyotiraditya/05c5853dd45257c35a3cb6cceb633624 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re | |
import sys | |
import xml.etree.ElementTree as ET | |
from typing import Dict, List, Union | |
def clean_key(key_text: str) -> str: | |
key_text = re.sub(r"-+BEGIN.*?-+|-+END.*?-+", "", key_text, flags=re.DOTALL) | |
return "".join(key_text.split()) | |
def parse_keybox_xml(xml_file: str) -> Dict[str, Dict[str, Union[str, List[str]]]]: | |
try: | |
tree = ET.parse(xml_file) | |
root = tree.getroot() | |
result = { | |
"EC": {"PRIV": "", "CERTS": ["", "", ""]}, | |
"RSA": {"PRIV": "", "CERTS": ["", "", ""]}, | |
} | |
for key in root.findall(".//Key"): | |
algorithm = key.get("algorithm") | |
if algorithm in ["ecdsa", "rsa"]: | |
key_type = "EC" if algorithm == "ecdsa" else "RSA" | |
result[key_type]["PRIV"] = clean_key(key.find(".//PrivateKey").text) | |
certs = key.findall(".//Certificate") | |
for i, cert in enumerate(certs[:3]): | |
result[key_type]["CERTS"][i] = clean_key(cert.text) | |
return result | |
except ET.ParseError as e: | |
raise ValueError(f"Invalid XML file: {e}") | |
except AttributeError as e: | |
raise ValueError(f"Unexpected XML structure: {e}") | |
def generate_string_array(keybox_data: Dict) -> str: | |
output = "" | |
# Add EC private key | |
output += f'<item>EC.PRIV:{keybox_data["EC"]["PRIV"]}</item>\n' | |
# Add EC certificates | |
for i, cert in enumerate(keybox_data["EC"]["CERTS"]): | |
output += f"<item>EC.CERT_{i+1}:{cert}</item>\n" | |
# Add RSA private key | |
output += f'<item>RSA.PRIV:{keybox_data["RSA"]["PRIV"]}</item>\n' | |
# Add RSA certificates | |
for i, cert in enumerate(keybox_data["RSA"]["CERTS"]): | |
output += f"<item>RSA.CERT_{i+1}:{cert}</item>\n" | |
return output | |
def main(): | |
if len(sys.argv) < 2: | |
print("Usage: python convert-key.py keybox.xml") | |
print("Converts keybox XML file to item entries for string-array config") | |
return 1 | |
try: | |
# Parse the XML file | |
keybox_data = parse_keybox_xml(sys.argv[1]) | |
# Generate and print string-array format | |
string_array_output = generate_string_array(keybox_data) | |
print(string_array_output) | |
except Exception as e: | |
print(f"Error: {e}", file=sys.stderr) | |
return 1 | |
return 0 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment