pyssh2age 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyssh2age
3
+ Version: 1.0.0
4
+ Summary: Convert SSH Ed25519 keys to age keys (pure-Python port of ssh-to-age)
5
+ Project-URL: Homepage, https://github.com/ivankra/pyssh2age
6
+ Project-URL: Source, https://github.com/ivankra/pyssh2age
7
+ Project-URL: Issues, https://github.com/ivankra/pyssh2age/issues
8
+ Author: Ivan Krasilnikov
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: age,ed25519,sops,sops-nix,ssh,x25519
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Operating System :: POSIX
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Topic :: Security :: Cryptography
21
+ Classifier: Topic :: Utilities
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+
25
+ # pyssh2age
26
+
27
+ Convert SSH Ed25519 keys to [age](https://github.com/FiloSottile/age) keys,
28
+ e.g. for [sops](https://github.com/getsops/sops) or [sops-nix](https://github.com/Mic92/sops-nix).
29
+
30
+ A single-file pure-Python port of [ssh-to-age](https://github.com/Mic92/ssh-to-age) that produces the same keys.
31
+ Python 3.9+, using only the standard library and `ssh-keygen` to decrypt passphrase-protected keys.
32
+
33
+ The conversion is the standard Ed25519 → X25519 mapping
34
+ ([explained here](https://blog.filippo.io/using-ed25519-keys-for-encryption/)):
35
+ the age secret is `sha512(seed)[:32]`, and the age public key is the Montgomery
36
+ u-coordinate of the Ed25519 public point, `u = (1 + y) / (1 - y)`.
37
+
38
+ ## Install
39
+
40
+ ```console
41
+ $ pipx install pyssh2age # or: uv tool install pyssh2age
42
+ ```
43
+
44
+ This installs the `pyssh2age` command and `ssh-to-age` alias.
45
+ Or copy [`src/pyssh2age.py`](https://github.com/ivankra/pyssh2age/blob/main/src/pyssh2age.py) anywhere and run it.
46
+
47
+ ## Usage
48
+
49
+ ```console
50
+ $ cat ~/.ssh/id_ed25519.pub | pyssh2age
51
+ age17044m9u...
52
+
53
+ $ pyssh2age -i ~/.ssh/id_ed25519.pub
54
+ age17044m9u...
55
+
56
+ $ ssh-keyscan host1 host2 | pyssh2age # or authorized_keys, known_hosts
57
+ skipped key: got ssh-rsa key type, but only ed25519 keys are supported
58
+ age1hjm3au...
59
+ age1v8zjc4...
60
+
61
+ $ pyssh2age --private-key -i ~/.ssh/id_ed25519 -o key.txt # see Security below
62
+ ```
63
+
64
+ Decrypting passphrase-protected private keys needs a Unix-like system;
65
+ everything else also works on Windows.
66
+
67
+ For a passphrase-protected key you're prompted on the terminal. In scripts,
68
+ use `--stdinpass` or `SSH_TO_AGE_PASSPHRASE`:
69
+
70
+ ```console
71
+ $ systemd-ask-password | pyssh2age --private-key --stdinpass -i ~/.ssh/id_ed25519 -o key.txt
72
+ ```
73
+
74
+ The age identity file (`-o`) is created with mode 0600, atomically replacing
75
+ any existing file. As in the Go version, options work with one or two dashes.
76
+
77
+ ## Library
78
+
79
+ ```python
80
+ import pyssh2age
81
+
82
+ pyssh2age.ssh_public_key_to_age("ssh-ed25519 AAAA... me@host") # "age1..."
83
+ pyssh2age.ssh_public_keys_to_age(open("authorized_keys").read()) # ["age1...", ...]
84
+
85
+ key = open("id_ed25519").read()
86
+ try:
87
+ identity = pyssh2age.ssh_private_key_to_age(key) # "AGE-SECRET-KEY-1..."
88
+ except pyssh2age.PassphraseRequired:
89
+ identity = pyssh2age.ssh_private_key_to_age(key, passphrase="...")
90
+ ```
91
+
92
+ Failures raise `ConvertError`; non-Ed25519 keys raise its subclass
93
+ `UnsupportedKeyType`. Lower-level helpers: `ed25519_public_to_x25519`,
94
+ `ed25519_seed_to_x25519`, `x25519_public`, `age_recipient`, `age_identity`.
95
+
96
+ ## Security
97
+
98
+ - **The age key is as powerful as the SSH key.** The original `id_ed25519` file you
99
+ derived it from can't be recovered, but it *is* the Ed25519 signing scalar:
100
+ whoever has it can sign as the SSH key and log in wherever that key is authorized.
101
+ - **Output file is written unencrypted** (as in the Go version),
102
+ even if the SSH key has a passphrase. Encrypt it with:
103
+ `pyssh2age --private-key ... | age -p -o key.txt.age`.
104
+
105
+ ## Development
106
+
107
+ The tests need `ssh-keygen` and `openssl`, and also check results with `age`
108
+ if it's installed:
109
+
110
+ ```console
111
+ $ python3 tests/test_pyssh2age.py
112
+ $ GO_SSH_TO_AGE=/path/to/ssh-to-age python3 tests/test_pyssh2age.py # also compare with the Go version
113
+ ```
114
+
115
+ ## License
116
+
117
+ MIT. Based on [ssh-to-age](https://github.com/Mic92/ssh-to-age) by Jörg Thalheim.
@@ -0,0 +1,6 @@
1
+ pyssh2age.py,sha256=eTUxrWVsXjUomWiBfhS6f60oAqKXRHw8z-_L93OEzLU,35150
2
+ pyssh2age-1.0.0.dist-info/METADATA,sha256=bhpW6_nf6jeAlk79XudZFzLRbCc1n4_PR49XwJATbFY,4262
3
+ pyssh2age-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ pyssh2age-1.0.0.dist-info/entry_points.txt,sha256=52EKGlrTTx3xShzAHFaNYZv-fP6xXzQAFamJal7uRuA,73
5
+ pyssh2age-1.0.0.dist-info/licenses/LICENSE,sha256=p7bPOepi5NhGGr6n_zIkdxMb2yzqUpc_KM2shAmXQao,1220
6
+ pyssh2age-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pyssh2age = pyssh2age:main
3
+ ssh-to-age = pyssh2age:main
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ivan Krasilnikov (Python port)
4
+ Copyright (c) 2022 Jörg Thalheim (ssh-to-age)
5
+ Copyright (c) 2019 Google LLC (bech32)
6
+ Copyright (c) 2017 Takatoshi Nakagawa (bech32)
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
pyssh2age.py ADDED
@@ -0,0 +1,870 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-FileCopyrightText: 2026 Ivan Krasilnikov (Python port)
3
+ # SPDX-FileCopyrightText: 2022 Jörg Thalheim (ssh-to-age)
4
+ # SPDX-FileCopyrightText: 2019 Google LLC (bech32)
5
+ # SPDX-FileCopyrightText: 2017 Takatoshi Nakagawa (bech32)
6
+ # SPDX-License-Identifier: MIT
7
+ """pyssh2age: convert SSH Ed25519 keys to age X25519 keys.
8
+
9
+ Python port of https://github.com/Mic92/ssh-to-age using only the standard
10
+ library and `ssh-keygen` to decrypt passphrase-protected ssh keys.
11
+
12
+ Usage (pip installs it as `pyssh2age` plus `ssh-to-age` alias):
13
+
14
+ cat ~/.ssh/id_ed25519.pub | pyssh2age # convert your public key
15
+ cat /etc/ssh/ssh_host_ed25519_key.pub | pyssh2age # convert sshd's public key
16
+ ssh-keyscan host | pyssh2age # many keys, non-Ed25519 skipped
17
+ pyssh2age --private-key -i ~/.ssh/id_ed25519 # convert private key
18
+
19
+ Works as a library too:
20
+
21
+ import pyssh2age
22
+ pyssh2age.ssh_public_key_to_age("ssh-ed25519 AAAA... me@host") # "age1..."
23
+ pyssh2age.ssh_public_keys_to_age(open("authorized_keys").read()) # ["age1...", ...]
24
+ pyssh2age.ssh_private_key_to_age(open("id_ed25519").read(), passphrase="...")
25
+
26
+ Before converting private keys, read "Security" section in README.md:
27
+ the age identity is as powerful as the SSH key, and is written unencrypted.
28
+
29
+ Needs Python >= 3.9. Decrypting passphrase-protected private keys needs
30
+ a Unix-like system with `ssh-keygen`, everything else also works on Windows.
31
+
32
+ Encrypted keys need bcrypt_pbkdf + AES/ChaCha, which the standard library
33
+ lacks, so we run `ssh-keygen -p -N ""` on a copy of the key in a private
34
+ 0700 temp dir and parse the decrypted result. The passphrase is typed into
35
+ ssh-keygen's prompt over a pseudo-terminal, so it never shows up in argv or
36
+ the environment. So, unfortunately, the decrypted copy briefly exists
37
+ as a file, but `ssh-keygen -p` doesn't lend itself to being used with a pipe.
38
+ The copy is removed right away (when run as a command, also on SIGTERM/SIGHUP).
39
+ As a library, note that decrypting forks (pty.fork) to run ssh-keygen.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import argparse
45
+ import base64
46
+ import contextlib
47
+ import errno
48
+ import getpass
49
+ import hashlib
50
+ import os
51
+ import secrets
52
+ import selectors
53
+ import shutil
54
+ import signal
55
+ import stat
56
+ import struct
57
+ import sys
58
+ import tempfile
59
+ import time
60
+ from collections.abc import Callable
61
+
62
+ __version__ = "1.0.0"
63
+ __all__ = [
64
+ "ConvertError",
65
+ "PassphraseRequired",
66
+ "UnsupportedKeyType",
67
+ "__version__",
68
+ "age_identity",
69
+ "age_recipient",
70
+ "ed25519_public_to_x25519",
71
+ "ed25519_seed_to_x25519",
72
+ "main",
73
+ "ssh_private_key_to_age",
74
+ "ssh_public_key_to_age",
75
+ "ssh_public_keys_to_age",
76
+ "x25519_public",
77
+ ]
78
+
79
+ _ED25519 = "ssh-ed25519"
80
+
81
+
82
+ class ConvertError(Exception):
83
+ """A key could not be converted."""
84
+
85
+
86
+ class PassphraseRequired(ConvertError):
87
+ """The key is passphrase protected, but no passphrase was given."""
88
+
89
+
90
+ class UnsupportedKeyType(ConvertError):
91
+ """The key is not Ed25519."""
92
+
93
+
94
+ def _unsupported(key_type):
95
+ return UnsupportedKeyType(
96
+ f"got {key_type} key type, but only ed25519 keys are supported")
97
+
98
+
99
+ def _to_bytes(x):
100
+ if x is None:
101
+ return b""
102
+ return x.encode() if isinstance(x, str) else bytes(x)
103
+
104
+
105
+ def _check_len(name, data):
106
+ if len(data) != 32:
107
+ raise ConvertError(f"invalid {name} length {len(data)}, want 32")
108
+
109
+
110
+ # --------------------------------------------------------------------------
111
+ # bech32 (BIP173), encode only
112
+
113
+ _BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
114
+ _BECH32_GEN = (0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3)
115
+
116
+
117
+ def _bech32_polymod(values):
118
+ chk = 1
119
+ for v in values:
120
+ top = chk >> 25
121
+ chk = (chk & 0x1FFFFFF) << 5 ^ v
122
+ for i in range(5):
123
+ if (top >> i) & 1:
124
+ chk ^= _BECH32_GEN[i]
125
+ return chk
126
+
127
+
128
+ def _bech32_encode(hrp, data):
129
+ """Encode bytes with a human-readable prefix. Output is lowercase."""
130
+ hrp = hrp.lower()
131
+ # Regroup 8-bit bytes into 5-bit values (with padding).
132
+ acc = bits = 0
133
+ values = []
134
+ for b in data:
135
+ acc = (acc << 8) | b
136
+ bits += 8
137
+ while bits >= 5:
138
+ bits -= 5
139
+ values.append((acc >> bits) & 31)
140
+ if bits:
141
+ values.append((acc << (5 - bits)) & 31)
142
+ expanded = [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
143
+ mod = _bech32_polymod(expanded + values + [0] * 6) ^ 1
144
+ checksum = [(mod >> 5 * (5 - i)) & 31 for i in range(6)]
145
+ return hrp + "1" + "".join(_BECH32_CHARSET[v] for v in values + checksum)
146
+
147
+
148
+ def age_recipient(x25519_pub: bytes) -> str:
149
+ """Encode a 32-byte X25519 public key as an age recipient ("age1...")."""
150
+ _check_len("X25519 public key", x25519_pub)
151
+ return _bech32_encode("age", x25519_pub)
152
+
153
+
154
+ def age_identity(x25519_secret: bytes) -> str:
155
+ """Encode a 32-byte X25519 secret as an age identity ("AGE-SECRET-KEY-1...")."""
156
+ _check_len("X25519 secret", x25519_secret)
157
+ return _bech32_encode("AGE-SECRET-KEY-", x25519_secret).upper()
158
+
159
+
160
+ # --------------------------------------------------------------------------
161
+ # Ed25519 -> X25519
162
+
163
+ _P = 2**255 - 19
164
+ _D = -121665 * pow(121666, _P - 2, _P) % _P
165
+
166
+
167
+ def ed25519_public_to_x25519(pub: bytes) -> bytes:
168
+ """Return the X25519 (Montgomery) form of a 32-byte Ed25519 public key."""
169
+ _check_len("ed25519 public key", pub)
170
+ # Like filippo.io/edwards25519 SetBytes: non-canonical y is accepted, but
171
+ # the encoding must be a point on the curve (x^2 = (y^2-1)/(d*y^2+1)
172
+ # must have a square root).
173
+ y = (int.from_bytes(pub, "little") & ((1 << 255) - 1)) % _P
174
+ yy = y * y % _P
175
+ x2 = (yy - 1) * pow(_D * yy + 1, _P - 2, _P) % _P
176
+ if x2 != 0 and pow(x2, (_P - 1) // 2, _P) != 1:
177
+ raise ConvertError(
178
+ "cannot convert ed25519 public key to curve25519: "
179
+ "invalid point encoding")
180
+ u = (1 + y) * pow((1 - y) % _P, _P - 2, _P) % _P
181
+ return u.to_bytes(32, "little")
182
+
183
+
184
+ def ed25519_seed_to_x25519(seed: bytes) -> bytes:
185
+ """Return the X25519 secret for a 32-byte Ed25519 seed (private key)."""
186
+ _check_len("ed25519 seed", seed)
187
+ return hashlib.sha512(seed).digest()[:32]
188
+
189
+
190
+ def x25519_public(secret: bytes) -> bytes:
191
+ """Return the X25519 public key for a 32-byte secret (RFC 7748)."""
192
+ _check_len("X25519 secret", secret)
193
+ return _x25519(secret, 9)
194
+
195
+
196
+ def _x25519(scalar, u):
197
+ """RFC 7748 X25519(scalar, u) via the Montgomery ladder. Not constant
198
+ time, which is fine for converting keys locally."""
199
+ k = int.from_bytes(scalar, "little")
200
+ k = (k & ~7 & ((1 << 255) - 1)) | (1 << 254) # clamp
201
+ x2, z2, x3, z3, swap = 1, 0, u, 1, 0
202
+ for t in range(254, -1, -1):
203
+ bit = (k >> t) & 1
204
+ if swap ^ bit:
205
+ x2, x3, z2, z3 = x3, x2, z3, z2
206
+ swap = bit
207
+ a, b = x2 + z2, x2 - z2
208
+ aa, bb = a * a % _P, b * b % _P
209
+ e = aa - bb
210
+ da, cb = (x3 - z3) * a % _P, (x3 + z3) * b % _P
211
+ x3, z3 = (da + cb) ** 2 % _P, u * (da - cb) ** 2 % _P
212
+ x2, z2 = aa * bb % _P, e * (aa + 121665 * e) % _P
213
+ if swap:
214
+ x2, z2 = x3, z3
215
+ return (x2 * pow(z2, _P - 2, _P) % _P).to_bytes(32, "little")
216
+
217
+
218
+ # --------------------------------------------------------------------------
219
+ # SSH wire format
220
+
221
+ def _ssh_string(b):
222
+ return struct.pack(">I", len(b)) + b
223
+
224
+
225
+ class _SSHWireReader:
226
+ def __init__(self, data):
227
+ self.data = data
228
+ self.pos = 0
229
+
230
+ def take(self, n):
231
+ if self.pos + n > len(self.data):
232
+ raise ConvertError("truncated data")
233
+ out = self.data[self.pos:self.pos + n]
234
+ self.pos += n
235
+ return out
236
+
237
+ def uint32(self):
238
+ return struct.unpack(">I", self.take(4))[0]
239
+
240
+ def string(self):
241
+ return self.take(self.uint32())
242
+
243
+ def rest(self):
244
+ out = self.data[self.pos:]
245
+ self.pos = len(self.data)
246
+ return out
247
+
248
+
249
+ # --------------------------------------------------------------------------
250
+ # Public keys (authorized_keys, known_hosts, ssh-keyscan output)
251
+
252
+ def _key_at_start(s):
253
+ """Return (type, blob) if s starts with "<type> <base64-blob>", else None."""
254
+ fields = s.split(None, 2)
255
+ if len(fields) < 2:
256
+ return None
257
+ try:
258
+ blob = base64.b64decode(fields[1], validate=True)
259
+ blob_type = _SSHWireReader(blob).string()
260
+ except (ValueError, ConvertError):
261
+ return None
262
+ return (fields[0], blob) if blob_type == fields[0].encode() else None
263
+
264
+
265
+ def _drop_field(s):
266
+ """Drop the first whitespace-delimited field, honouring "quoted" spans
267
+ (authorized_keys options such as command="a b")."""
268
+ in_quote = escaped = False
269
+ for i, c in enumerate(s):
270
+ if escaped:
271
+ escaped = False
272
+ elif c == "\\":
273
+ escaped = True
274
+ elif c == '"':
275
+ in_quote = not in_quote
276
+ elif c.isspace() and not in_quote:
277
+ return s[i:].lstrip()
278
+ return ""
279
+
280
+
281
+ def ssh_public_key_to_age(line: str | bytes) -> str:
282
+ """Convert one SSH public key line to an age recipient ("age1...").
283
+
284
+ Accepted layouts (the key is only looked for at its designated position):
285
+ <type> <blob> [comment] plain / authorized_keys
286
+ <options> <type> <blob> [comment] authorized_keys
287
+ [@marker] <hosts> <type> <blob> [comment] known_hosts, ssh-keyscan
288
+
289
+ Raises UnsupportedKeyType for any key that isn't ssh-ed25519 (RSA, ECDSA,
290
+ FIDO, certificates, ML-DSA, types that don't exist yet, ...) without
291
+ inspecting it further: it can never yield a recipient, so callers should
292
+ be able to skip it. A malformed ssh-ed25519 key raises ConvertError.
293
+ """
294
+ if isinstance(line, bytes):
295
+ line = line.decode("utf-8", "replace")
296
+ line = line.strip()
297
+ if "\n" in line:
298
+ raise ConvertError("failed to parse ssh public key: expected a single line; "
299
+ "use ssh_public_keys_to_age() for multiple keys")
300
+ rest = _drop_field(line) if line.startswith("@") else line
301
+ found = _key_at_start(rest) or _key_at_start(_drop_field(rest))
302
+ if found is None:
303
+ raise ConvertError("failed to parse ssh public key: no key found")
304
+ key_type, blob = found
305
+ if key_type != _ED25519:
306
+ raise _unsupported(key_type)
307
+ r = _SSHWireReader(blob)
308
+ r.string() # key type
309
+ try:
310
+ pub = r.string()
311
+ except ConvertError:
312
+ raise ConvertError("failed to parse ssh public key: truncated ssh-ed25519 key") from None
313
+ if r.rest():
314
+ raise ConvertError("failed to parse ssh public key: trailing data")
315
+ return age_recipient(ed25519_public_to_x25519(pub))
316
+
317
+
318
+ def _iter_public_keys(text, on_skip):
319
+ if isinstance(text, bytes):
320
+ text = text.decode("utf-8", "replace")
321
+ for line in text.split("\n"):
322
+ line = line.strip()
323
+ if not line or line.startswith("#"):
324
+ continue
325
+ try:
326
+ yield ssh_public_key_to_age(line)
327
+ except UnsupportedKeyType as e:
328
+ if on_skip is not None:
329
+ on_skip(line, e)
330
+ except ConvertError as e:
331
+ raise ConvertError(f"failed to convert '{line}': {e}") from None
332
+
333
+
334
+ def ssh_public_keys_to_age(
335
+ text: str | bytes,
336
+ on_skip: Callable[[str, UnsupportedKeyType], None] | None = None,
337
+ ) -> list[str]:
338
+ """Convert every key in authorized_keys / known_hosts / ssh-keyscan
339
+ style text (one key per line; blank and # lines ignored) to age
340
+ recipients. Non-ed25519 keys are skipped, reported to on_skip(line, err)
341
+ if given. A malformed line raises ConvertError."""
342
+ return list(_iter_public_keys(text, on_skip))
343
+
344
+
345
+ # --------------------------------------------------------------------------
346
+ # Private keys
347
+
348
+ _OPENSSH_MAGIC = b"openssh-key-v1\0"
349
+
350
+
351
+ def _openssh_pem(der):
352
+ """A clean OpenSSH PEM file for der (LF line endings, no extra text)."""
353
+ b64 = base64.b64encode(der).decode()
354
+ lines = [b64[i:i + 70] for i in range(0, len(b64), 70)]
355
+ return "\n".join(["-----BEGIN OPENSSH PRIVATE KEY-----", *lines,
356
+ "-----END OPENSSH PRIVATE KEY-----", ""]).encode()
357
+
358
+
359
+ def _pem_decode(data):
360
+ """Return (label, der) for the first PEM block in data."""
361
+ text = data.decode("latin-1") # lossless; non-ASCII is rejected by b64decode
362
+ start = text.find("-----BEGIN ")
363
+ if start < 0:
364
+ raise ConvertError("failed to parse ssh private key: no key found")
365
+ label_end = text.find("-----", start + 11)
366
+ if label_end < 0:
367
+ raise ConvertError("failed to parse ssh private key: malformed PEM")
368
+ label = text[start + 11:label_end]
369
+ end_marker = f"-----END {label}-----"
370
+ end = text.find(end_marker, label_end)
371
+ if end < 0:
372
+ raise ConvertError("failed to parse ssh private key: malformed PEM")
373
+ # drop legacy "Proc-Type: 4,ENCRYPTED" style headers (RSA/EC/DSA keys only)
374
+ body = "".join("".join(ln.split()) for ln in text[label_end + 5:end].splitlines()
375
+ if ":" not in ln)
376
+ try:
377
+ return label, base64.b64decode(body, validate=True)
378
+ except ValueError as e: # binascii.Error, or non-ASCII characters
379
+ raise ConvertError(f"failed to parse ssh private key: {e}") from None
380
+
381
+
382
+ def _parse_openssh_private(der):
383
+ """Parse an ed25519 openssh-key-v1 blob. Returns (cipher, seed), where
384
+ seed is None if the key is encrypted."""
385
+ if not der.startswith(_OPENSSH_MAGIC):
386
+ raise ConvertError("failed to parse ssh private key: invalid openssh key magic")
387
+ r = _SSHWireReader(der[len(_OPENSSH_MAGIC):])
388
+ cipher = r.string().decode("ascii", "replace")
389
+ kdf = r.string()
390
+ kdf_options = r.string()
391
+ if cipher == "none" and (kdf != b"none" or kdf_options):
392
+ raise ConvertError("failed to parse ssh private key: unencrypted key with a KDF")
393
+ if r.uint32() != 1:
394
+ raise ConvertError("failed to parse ssh private key: multi-key files are not supported")
395
+ outer_pub = r.string()
396
+ pub_type = _SSHWireReader(outer_pub).string().decode("ascii", "replace")
397
+ if pub_type != _ED25519: # checked before needing a passphrase
398
+ raise _unsupported(pub_type)
399
+ if cipher != "none":
400
+ return cipher, None
401
+
402
+ priv = _SSHWireReader(r.string())
403
+ if priv.uint32() != priv.uint32():
404
+ raise ConvertError("failed to parse ssh private key: check bytes mismatch")
405
+ key_type = priv.string().decode("ascii", "replace")
406
+ if key_type != _ED25519:
407
+ raise _unsupported(key_type)
408
+ pub = priv.string()
409
+ sk = priv.string()
410
+ priv.string() # comment
411
+ pad = priv.rest()
412
+ if any(b != i + 1 for i, b in enumerate(pad)):
413
+ raise ConvertError("failed to parse ssh private key: invalid padding")
414
+ if len(sk) != 64 or len(pub) != 32 or sk[32:] != pub:
415
+ raise ConvertError("failed to parse ssh private key: malformed ed25519 key")
416
+ # The seed must actually belong to the stored public keys, or we'd emit
417
+ # an identity that can't decrypt for the key's advertised recipient.
418
+ seed = sk[:32]
419
+ if (outer_pub != _ssh_string(_ED25519.encode()) + _ssh_string(pub)
420
+ or x25519_public(ed25519_seed_to_x25519(seed)) != ed25519_public_to_x25519(pub)):
421
+ raise ConvertError("failed to parse ssh private key: "
422
+ "private key does not match its public key")
423
+ return cipher, seed
424
+
425
+
426
+ def _malformed_pkcs8():
427
+ return ConvertError("failed to parse ssh private key: malformed PKCS#8 key")
428
+
429
+
430
+ def _der(data, pos, tag):
431
+ """Read the DER element at pos, which must have the given tag.
432
+ Returns (value, next_pos)."""
433
+ if pos + 2 > len(data) or data[pos] != tag:
434
+ raise _malformed_pkcs8()
435
+ length = data[pos + 1]
436
+ pos += 2
437
+ if length & 0x80:
438
+ n = length & 0x7F
439
+ length = int.from_bytes(data[pos:pos + n], "big")
440
+ pos += n
441
+ if pos + length > len(data):
442
+ raise _malformed_pkcs8()
443
+ return data[pos:pos + length], pos + length
444
+
445
+
446
+ _ED25519_OID = b"\x2b\x65\x70" # 1.3.101.112
447
+
448
+
449
+ def _parse_pkcs8_private(der):
450
+ """Parse an unencrypted PKCS#8 (RFC 8410) Ed25519 key. Returns the seed."""
451
+ body, _ = _der(der, 0, 0x30) # PrivateKeyInfo
452
+ _, pos = _der(body, 0, 0x02) # version
453
+ alg, pos = _der(body, pos, 0x30) # AlgorithmIdentifier
454
+ oid, end = _der(alg, 0, 0x06)
455
+ if oid != _ED25519_OID: # before parsing the algorithm-specific payload
456
+ raise _unsupported("pkcs8 non-ed25519")
457
+ octets, _ = _der(body, pos, 0x04) # privateKey
458
+ seed, _ = _der(octets, 0, 0x04) # CurvePrivateKey
459
+ if end != len(alg) or len(seed) != 32: # RFC 8410: no algorithm parameters
460
+ raise _malformed_pkcs8()
461
+ return seed
462
+
463
+
464
+ # How long to wait for ssh-keygen's passphrase prompt. There is no limit after
465
+ # answering it: key derivation takes ~1s per 100 bcrypt rounds (`-a`).
466
+ _PROMPT_TIMEOUT = 30 # seconds
467
+
468
+
469
+ def _safe_parent(d):
470
+ """Return d with symlinks resolved if no other user can redirect or
471
+ replace it or anything we create inside it, else None.
472
+
473
+ Every component of the resolved path, from / down, must be owned by us
474
+ or root, and not group/world-writable unless sticky (like /tmp, where
475
+ others can't rename entries they don't own). The resolved path is then
476
+ used for the whole operation, so a symlink can't be swapped later.
477
+ """
478
+ d = os.path.realpath(d)
479
+ if not os.path.isdir(d) or not os.access(d, os.W_OK | os.X_OK):
480
+ return None
481
+ euid = os.geteuid()
482
+ path = d
483
+ while True:
484
+ try:
485
+ st = os.lstat(path)
486
+ except OSError:
487
+ return None
488
+ if (stat.S_ISLNK(st.st_mode) or st.st_uid not in (0, euid)
489
+ or (st.st_mode & 0o022 and not st.st_mode & stat.S_ISVTX)):
490
+ return None
491
+ parent = os.path.dirname(path)
492
+ if parent == path:
493
+ return d
494
+ path = parent
495
+
496
+
497
+ def _tmp_parent():
498
+ """Pick where the temporary key copy goes. Prefers a tmpfs (nothing hits
499
+ the disk), and only uses directories other users can't tamper with."""
500
+ candidates = (os.environ.get("XDG_RUNTIME_DIR"), "/dev/shm", tempfile.gettempdir())
501
+ for d in candidates:
502
+ if d and (safe := _safe_parent(d)):
503
+ return safe
504
+ raise ConvertError("no safe temporary directory (private, or sticky like "
505
+ "/tmp) found; tried: " + ", ".join(filter(None, candidates)))
506
+
507
+
508
+ def _write_all(fd, data):
509
+ while data:
510
+ data = data[os.write(fd, data):]
511
+
512
+
513
+ def _run_with_tty_passphrase(argv, passphrase):
514
+ """Run argv on a fresh pseudo-terminal and type passphrase at its prompt.
515
+
516
+ Returns (wait_status, terminal_output); wait_status is 0 on success. No
517
+ askpass helper is executed and the passphrase never appears in argv or
518
+ the environment. Unix only.
519
+ """
520
+ import pty # Unix only, so imported only when decrypting
521
+ import tty
522
+
523
+ env = {k: v for k, v in os.environb.items()
524
+ if not k.startswith(b"SSH_ASKPASS") # e.g. SSH_ASKPASS_REQUIRE=force
525
+ and k != b"SSH_TO_AGE_PASSPHRASE"}
526
+ pid, master = pty.fork()
527
+ if pid == 0: # child: raw tty, so control characters in the passphrase
528
+ try: # are not interpreted; then exec ssh-keygen
529
+ tty.setraw(0)
530
+ os.execve(argv[0], argv, env)
531
+ finally:
532
+ os._exit(127)
533
+
534
+ output = b""
535
+ since_answer = None # output offset after we typed the passphrase
536
+ # epoll/kqueue: unlike select(), fine with fds >= 1024 in busy processes
537
+ sel = selectors.DefaultSelector()
538
+ try:
539
+ sel.register(master, selectors.EVENT_READ)
540
+ deadline = time.monotonic() + _PROMPT_TIMEOUT
541
+ while True:
542
+ timeout = None if since_answer else max(0, deadline - time.monotonic())
543
+ if not sel.select(timeout):
544
+ raise ConvertError("ssh-keygen did not ask for the passphrase")
545
+ try:
546
+ chunk = os.read(master, 4096)
547
+ except OSError: # EIO: child closed the terminal
548
+ chunk = b""
549
+ if not chunk:
550
+ break
551
+ output += chunk
552
+ tail = output[since_answer or 0:].rsplit(b"\n", 1)[-1].lower()
553
+ # readpassphrase() flushes pending input *before* printing the
554
+ # prompt, so the answer must only be sent once the prompt is seen.
555
+ if b"passphrase" in tail and tail.rstrip().endswith(b":"):
556
+ if since_answer:
557
+ raise ConvertError("incorrect passphrase")
558
+ _write_all(master, passphrase + b"\n")
559
+ since_answer = len(output)
560
+ except BaseException:
561
+ with contextlib.suppress(OSError):
562
+ os.kill(pid, signal.SIGKILL)
563
+ raise
564
+ finally:
565
+ sel.close()
566
+ os.close(master)
567
+ _, status = os.waitpid(pid, 0)
568
+ return status, output.decode(errors="replace")
569
+
570
+
571
+ _DECRYPT_A_COPY = "decrypt a copy first: ssh-keygen -p -N '' -f COPY_OF_KEY"
572
+ _MAX_TYPED_PASSPHRASE = 1024 # size of ssh-keygen's read_passphrase() buffer
573
+
574
+
575
+ def _decrypt_with_ssh_keygen(pem_block, passphrase):
576
+ """Strip the passphrase from a private copy of the key using ssh-keygen.
577
+ The copy lives in a 0700 temp dir (tmpfs when available) that is removed
578
+ afterwards."""
579
+ if os.name != "posix":
580
+ raise ConvertError("decrypting passphrase-protected keys needs a "
581
+ f"Unix-like system; {_DECRYPT_A_COPY}")
582
+ if any(c in passphrase for c in b"\r\n\0"):
583
+ raise ConvertError("passphrases containing line breaks or NUL bytes "
584
+ f"cannot be typed into ssh-keygen; {_DECRYPT_A_COPY}")
585
+ # ssh-keygen reads the passphrase into a 1024-byte buffer and silently
586
+ # truncates longer input, which would then fail as "incorrect passphrase".
587
+ if len(passphrase) >= _MAX_TYPED_PASSPHRASE:
588
+ raise ConvertError(f"passphrases of {_MAX_TYPED_PASSPHRASE} bytes or more "
589
+ f"cannot be typed into ssh-keygen; {_DECRYPT_A_COPY}")
590
+ ssh_keygen = shutil.which("ssh-keygen")
591
+ if ssh_keygen is None:
592
+ raise ConvertError("ssh-keygen not found in PATH; it is required to "
593
+ "decrypt passphrase-protected keys")
594
+ try:
595
+ with tempfile.TemporaryDirectory(prefix="ssh-to-age.", dir=_tmp_parent()) as tmp:
596
+ key_path = os.path.join(tmp, "key")
597
+ fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
598
+ with os.fdopen(fd, "wb") as f:
599
+ f.write(pem_block)
600
+ status, output = _run_with_tty_passphrase(
601
+ [ssh_keygen, "-p", "-q", "-N", "", "-f", key_path], passphrase)
602
+ if status != 0:
603
+ msg = " ".join(line.strip() for line in output.splitlines()
604
+ if line.strip() and "passphrase:" not in line)
605
+ raise ConvertError("ssh-keygen failed to decrypt key: "
606
+ + msg.replace(key_path, "key"))
607
+ with open(key_path, "rb") as f:
608
+ return f.read()
609
+ except OSError as e:
610
+ raise ConvertError(f"cannot decrypt key with ssh-keygen: {e}") from None
611
+
612
+
613
+ def ssh_private_key_to_age(key: str | bytes,
614
+ passphrase: str | bytes | None = None) -> str:
615
+ """Convert an SSH Ed25519 private key file's contents (OpenSSH or
616
+ PKCS#8 PEM) to an age identity ("AGE-SECRET-KEY-1...").
617
+
618
+ Encrypted OpenSSH keys need the passphrase (and ssh-keygen); like the Go
619
+ version, giving a passphrase for an unencrypted key is an error. Raises
620
+ PassphraseRequired for an encrypted key without passphrase (e.g. ask the
621
+ user and call again), UnsupportedKeyType for non-ed25519 keys, and
622
+ ConvertError otherwise.
623
+ """
624
+ passphrase = _to_bytes(passphrase)
625
+ label, der = _pem_decode(_to_bytes(key))
626
+ if label == "PRIVATE KEY":
627
+ cipher, seed = "none", _parse_pkcs8_private(der)
628
+ elif label == "OPENSSH PRIVATE KEY":
629
+ cipher, seed = _parse_openssh_private(der) # seed is None if encrypted
630
+ elif label == "ENCRYPTED PRIVATE KEY": # PKCS#8 EncryptedPrivateKeyInfo
631
+ raise ConvertError("encrypted PKCS#8 keys are not supported; decrypt a "
632
+ "copy first: openssl pkey -in KEY -out COPY_OF_KEY")
633
+ else:
634
+ raise _unsupported(label.replace(" PRIVATE KEY", "").lower() or label)
635
+ if seed is not None and passphrase:
636
+ raise ConvertError("key is not password protected, but a passphrase was "
637
+ "supplied (unset SSH_TO_AGE_PASSPHRASE / drop --stdinpass)")
638
+ if seed is None:
639
+ if not passphrase:
640
+ raise PassphraseRequired(f"this private key is passphrase protected ({cipher}); "
641
+ "use --stdinpass or SSH_TO_AGE_PASSPHRASE")
642
+ plain = _decrypt_with_ssh_keygen(_openssh_pem(der), passphrase)
643
+ _, seed = _parse_openssh_private(_pem_decode(plain)[1])
644
+ if seed is None:
645
+ raise ConvertError("ssh-keygen did not produce an unencrypted key")
646
+ return age_identity(ed25519_seed_to_x25519(seed))
647
+
648
+
649
+ # --------------------------------------------------------------------------
650
+ # CLI (same options as the Go ssh-to-age, which used single-dash long ones)
651
+
652
+ def _open_output(path):
653
+ """Open the (public key) output file, or stdout for "-". Lines end in
654
+ "\n" like Go's, also on Windows."""
655
+ if path == "-":
656
+ return open(sys.stdout.fileno(), "w", newline="\n", closefd=False)
657
+ return open(path, "w", newline="\n")
658
+
659
+
660
+ # Directory-fd based file operations; missing on Windows, where secrets are
661
+ # then written in place like Go does (an existing file keeps its ACL, a new
662
+ # one inherits the directory's).
663
+ _DIR_FD_OK = (hasattr(os, "O_DIRECTORY") and hasattr(os, "O_NOFOLLOW")
664
+ and {os.open, os.readlink, os.rename} <= os.supports_dir_fd)
665
+
666
+
667
+ def _output_fd(path):
668
+ """The inherited descriptor that path names ("-", /dev/stdout,
669
+ /dev/stderr, /dev/fd/N, /proc/self/fd/N), or None."""
670
+ if path in ("-", "/dev/stdout"):
671
+ return 1
672
+ if path == "/dev/stderr":
673
+ return 2
674
+ for prefix in ("/dev/fd/", "/proc/self/fd/"):
675
+ n = path.removeprefix(prefix)
676
+ if n != path and n.isascii() and n.isdigit() and int(n) < 2**31:
677
+ return int(n)
678
+ return None
679
+
680
+
681
+ def _open_output_dir(path):
682
+ """Follow path like open() would (symlinks in the last component
683
+ included), but with every lookup done by the OS rather than textually
684
+ like realpath(): "missing/../f", "file/../f" and links pointing at such
685
+ paths fail. Returns (fd of the final parent directory, final name, None),
686
+ or (None, None, fd) if a link leads to /dev/stdout, /dev/fd/N etc."""
687
+ for _ in range(40): # like the kernel's symlink limit
688
+ fd_no = _output_fd(path) if path != "-" else None # a link to "-" is a file
689
+ if fd_no is not None:
690
+ return None, None, fd_no
691
+ parent, name = os.path.split(path)
692
+ if name in ("", ".", ".."): # "file/", "dir/.": not a file name
693
+ code = errno.EISDIR if os.path.isdir(path) else errno.ENOTDIR
694
+ raise OSError(code, os.strerror(code))
695
+ dfd = os.open(parent or ".", os.O_RDONLY | os.O_DIRECTORY)
696
+ try:
697
+ link = os.readlink(name, dir_fd=dfd)
698
+ except OSError as e:
699
+ if e.errno in (errno.EINVAL, errno.ENOENT): # not a symlink / missing
700
+ return dfd, name, None
701
+ os.close(dfd)
702
+ raise
703
+ os.close(dfd)
704
+ path = os.path.join(parent, link) # absolute link targets replace parent
705
+ raise OSError(errno.ELOOP, os.strerror(errno.ELOOP))
706
+
707
+
708
+ def _write_secret(path, text):
709
+ """Write a secret to path.
710
+
711
+ - "-", /dev/stdout, /dev/stderr, /dev/fd/N, /proc/self/fd/N (also when
712
+ reached through a symlink): written to that inherited descriptor, so
713
+ shell redirections (incl. >>) work.
714
+ - Other non-regular files (FIFO, tty, ...): written through directly.
715
+ - Regular files are never written in place: the secret goes into a fresh
716
+ 0600 file owned by the current user in the same directory, which then
717
+ atomically replaces the destination. So it never lands in an inode that
718
+ someone may already have open, or that has looser permissions or another
719
+ owner (chown it afterwards if a different owner is wanted). A symlink
720
+ destination is followed and its target replaced. (On Windows, written
721
+ in place instead; see _DIR_FD_OK.)
722
+ """
723
+ data = text.encode()
724
+ try:
725
+ fd_no = _output_fd(path)
726
+ if fd_no is None and not _DIR_FD_OK:
727
+ # Windows: write in place, like Go. A replacement file would get
728
+ # the directory's ACL instead of a (stricter) existing file's.
729
+ with open(path, "wb") as f:
730
+ f.write(data)
731
+ return
732
+ if fd_no is None:
733
+ # Everything below is relative to an fd of the final parent
734
+ # directory: it can't be swapped under us, and neither the check
735
+ # nor the rename follows a symlink that appears in place of the
736
+ # destination in the meantime.
737
+ dfd, name, fd_no = _open_output_dir(path)
738
+ if fd_no is not None:
739
+ _write_all(fd_no, data)
740
+ return
741
+ try:
742
+ # Open without O_CREAT/O_TRUNC (harmless for a regular file) and
743
+ # check what we actually got: FIFOs, ttys etc. are written through.
744
+ try:
745
+ fd = os.open(name, os.O_WRONLY | os.O_NOFOLLOW, dir_fd=dfd)
746
+ except OSError as e:
747
+ # missing, or a symlink now (ELOOP; EMLINK on FreeBSD)
748
+ if e.errno not in (errno.ENOENT, errno.ELOOP, errno.EMLINK):
749
+ raise
750
+ else:
751
+ with os.fdopen(fd, "wb") as f:
752
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
753
+ f.write(data)
754
+ return
755
+ # short fixed name: a long destination name must still fit
756
+ tmp = f".pyssh2age.{secrets.token_hex(8)}.tmp"
757
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=dfd)
758
+ try:
759
+ with os.fdopen(fd, "wb") as f:
760
+ f.write(data)
761
+ f.flush()
762
+ os.fsync(fd)
763
+ os.replace(tmp, name, src_dir_fd=dfd, dst_dir_fd=dfd)
764
+ except BaseException:
765
+ with contextlib.suppress(OSError):
766
+ os.unlink(tmp, dir_fd=dfd)
767
+ raise
768
+ finally:
769
+ os.close(dfd)
770
+ except OSError as e:
771
+ raise ConvertError(f"failed to write {path}: {e.strerror}") from None
772
+
773
+
774
+ def _ask_passphrase():
775
+ """Prompt on the terminal without echo; Enter ends it, Ctrl-D gives none."""
776
+ try:
777
+ return os.fsencode(getpass.getpass("Enter passphrase: "))
778
+ except EOFError:
779
+ print(file=sys.stderr) # end the prompt line
780
+ return b""
781
+
782
+
783
+ def main(argv: list[str] | None = None) -> None:
784
+ """Run the command line tool; argv is like sys.argv (argv[0] is the
785
+ program name). On failure, exits with an error message (SystemExit)."""
786
+ argv = sys.argv if argv is None else argv
787
+ p = argparse.ArgumentParser(
788
+ prog=os.path.basename(argv[0]) if argv else "pyssh2age",
789
+ description="Convert SSH Ed25519 keys to age keys.",
790
+ allow_abbrev=False)
791
+ def flag(name, *aliases, **kw): # like Go's flag package: -name or --name
792
+ p.add_argument(f"-{name}", f"--{name}", *aliases, **kw)
793
+ flag("private-key", action="store_true",
794
+ help="convert a private key instead of public keys")
795
+ flag("i", "--input", dest="input", default="-", metavar="PATH",
796
+ help="input path (default: standard input)")
797
+ flag("o", "--output", dest="output", default="-", metavar="PATH",
798
+ help="output path (default: standard output)")
799
+ flag("stdinpass", action="store_true",
800
+ help="read the private key passphrase from standard input")
801
+ flag("version", action="version", version=__version__)
802
+ opts = p.parse_args(argv[1:])
803
+
804
+ # SIGTERM/SIGHUP unwind like Ctrl-C, so a decrypted temp copy of the key is removed.
805
+ for name in ("SIGTERM", "SIGHUP"):
806
+ if hasattr(signal, name):
807
+ signal.signal(getattr(signal, name), lambda signum, _: sys.exit(128 + signum))
808
+ try:
809
+ _convert(opts)
810
+ except ConvertError as e:
811
+ sys.exit(f"{argv[0] if argv else p.prog}: {e}")
812
+ except KeyboardInterrupt:
813
+ sys.exit(130)
814
+ except BrokenPipeError: # stdout reader went away, e.g. `| head`: exit quietly
815
+ sys.exit(1)
816
+
817
+
818
+ def _convert(opts):
819
+ """Do what the parsed command line asks. Raises ConvertError on failure."""
820
+ if opts.private_key and opts.stdinpass and opts.input == "-":
821
+ raise ConvertError("cannot read both private key and passphrase from stdin")
822
+ try:
823
+ if opts.input == "-":
824
+ data, in_st = sys.stdin.buffer.read(), os.fstat(sys.stdin.fileno())
825
+ else:
826
+ with open(opts.input, "rb") as f:
827
+ data, in_st = f.read(), os.fstat(f.fileno())
828
+ except OSError as e:
829
+ raise ConvertError(f"error reading {opts.input}: {e.strerror}") from None
830
+ # Writing over the input would destroy the SSH key: -i key -o key, also
831
+ # through symlinks, hard links, or `< key`.
832
+ if _output_fd(opts.output) is None:
833
+ with contextlib.suppress(OSError): # e.g. the output doesn't exist yet
834
+ out_st = os.stat(opts.output)
835
+ if (out_st.st_dev, out_st.st_ino) == (in_st.st_dev, in_st.st_ino):
836
+ raise ConvertError(f"refusing to overwrite the input {opts.input}")
837
+
838
+ if opts.private_key:
839
+ passphrase = os.fsencode(os.environ.get("SSH_TO_AGE_PASSPHRASE", ""))
840
+ if opts.stdinpass: # from a pipe, like Go; a terminal is prompted below
841
+ passphrase = b"" if sys.stdin.isatty() else sys.stdin.buffer.read().rstrip(b"\r\n")
842
+ try:
843
+ try:
844
+ key = ssh_private_key_to_age(data, passphrase)
845
+ except PassphraseRequired:
846
+ if not sys.stdin.isatty():
847
+ raise
848
+ key = ssh_private_key_to_age(data, _ask_passphrase())
849
+ except ConvertError as e:
850
+ # Unlike the Go version, never echo private key material.
851
+ name = "stdin" if opts.input == "-" else opts.input
852
+ raise ConvertError(f"failed to convert '{name}': {e}") from None
853
+ _write_secret(opts.output, key + "\n")
854
+ return
855
+
856
+ try:
857
+ with _open_output(opts.output) as out:
858
+ def skipped(_line, err):
859
+ out.flush() # keep stdout/stderr in input order
860
+ print(f"skipped key: {err}", file=sys.stderr)
861
+ for recipient in _iter_public_keys(data, skipped):
862
+ out.write(recipient + "\n")
863
+ except OSError as e: # open/write/close, e.g. disk full
864
+ if isinstance(e, BrokenPipeError) and _output_fd(opts.output) == 1:
865
+ raise # stdout reader went away, e.g. `| head`: quiet, see main()
866
+ raise ConvertError(f"failed to write {opts.output}: {e.strerror}") from None
867
+
868
+
869
+ if __name__ == "__main__":
870
+ main()