Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/ecdsa/ssh.py: 29%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import binascii
2from . import der
3from ._compat import compat26_str, int_to_bytes
5_SSH_ED25519 = b"ssh-ed25519"
6_SK_MAGIC = b"openssh-key-v1\0"
7_NONE = b"none"
10def _get_key_type(name):
11 if name == "Ed25519":
12 return _SSH_ED25519
13 else:
14 raise ValueError("Unsupported key type")
17class _Serializer:
18 def __init__(self):
19 self.bytes = b""
21 def put_raw(self, val):
22 self.bytes += val
24 def put_u32(self, val):
25 self.bytes += int_to_bytes(val, length=4, byteorder="big")
27 def put_str(self, val):
28 self.put_u32(len(val))
29 self.bytes += val
31 def put_pad(self, blklen=8):
32 padlen = blklen - (len(self.bytes) % blklen)
33 self.put_raw(bytearray(range(1, 1 + padlen)))
35 def encode(self):
36 return binascii.b2a_base64(compat26_str(self.bytes))
38 def tobytes(self):
39 return self.bytes
41 def topem(self):
42 return der.topem(self.bytes, "OPENSSH PRIVATE KEY")
45def serialize_public(name, pub):
46 serial = _Serializer()
47 ktype = _get_key_type(name)
48 serial.put_str(ktype)
49 serial.put_str(pub)
50 return b" ".join([ktype, serial.encode()])
53def serialize_private(name, pub, priv):
54 # encode public part
55 spub = _Serializer()
56 ktype = _get_key_type(name)
57 spub.put_str(ktype)
58 spub.put_str(pub)
60 # encode private part
61 spriv = _Serializer()
62 checksum = 0
63 spriv.put_u32(checksum)
64 spriv.put_u32(checksum)
65 spriv.put_raw(spub.tobytes())
66 spriv.put_str(priv + pub)
67 comment = b""
68 spriv.put_str(comment)
69 spriv.put_pad()
71 # top-level structure
72 main = _Serializer()
73 main.put_raw(_SK_MAGIC)
74 ciphername = kdfname = _NONE
75 main.put_str(ciphername)
76 main.put_str(kdfname)
77 nokdf = 0
78 main.put_u32(nokdf)
79 nkeys = 1
80 main.put_u32(nkeys)
81 main.put_str(spub.tobytes())
82 main.put_str(spriv.tobytes())
83 return main.topem()