Something went wrong. Try again.
A warm, tech-dystopian color scheme inspired by corrupted hardware and failing systems. digitalrust.katsuricata.com
theme color-scheme color-theme warm color
Something went wrong. Try again.
1.9 kB · 63 lines
Shell
at main
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#!/usr/bin/env python3"""write-ssh-key.sh — normalize a pasted OpenSSH private key back to canonicalPEM so ssh(1) accepts it, regardless of how a secrets UI stored it.
Handles the realistic ways a web "secret" field can mangle a multiline key:
* CRLF line endings (``\\r`` stripped)* missing trailing newline* the base64 body collapsed onto one line with spaces instead of newlines* leading/trailing whitespace
Usage: write-ssh-key.sh <output-path> (key content on stdin)
Prints the number of bytes written; exits non-zero with a diagnostic if theresult doesn't look like an OpenSSH private key."""import base64import reimport sys
KEY_RE = re.compile( r"-----BEGIN (?P<kind>OPENSSH|PRIVATE|RSA|EC|DSA)[^-]*PRIVATE KEY-----" r"(?P<body>.*?)" r"-----END (?P=kind)[^-]*PRIVATE KEY-----", re.DOTALL,)
def main() -> int: if len(sys.argv) != 2: print(__doc__) return 2 out = sys.argv[1] raw = sys.stdin.read() raw = raw.strip().replace("\r", "")
m = KEY_RE.search(raw) if not m: print("write-ssh-key: no PEM block found in the secret", file=sys.stderr) return 1 header = m.group(0).split("-----", 4)[1] kind = m.group("kind") # re-wrap the base64 body at 70 chars/line (OpenSSH's native width) body = re.sub(r"[^A-Za-z0-9+/=]", "", m.group("body")) try: base64.b64decode(body, validate=True) except Exception as e: # noqa: BLE001 print(f"write-ssh-key: base64 body is invalid: {e}", file=sys.stderr) return 1 lines = [body[i : i + 70] for i in range(0, len(body), 70)] block = ( f"-----BEGIN {kind} PRIVATE KEY-----\n" + "\n".join(lines) + f"\n-----END {kind} PRIVATE KEY-----\n" ) with open(out, "w") as fh: fh.write(block) print(f"normalized {kind} private key -> {out} ({len(block)} bytes)") return 0
if __name__ == "__main__": sys.exit(main())