Skip to content

Commit cd63ff0

Browse files
committed
fix: loading ssh keys from disk
1 parent 9272c1c commit cd63ff0

File tree

2 files changed

+29
-17
lines changed

2 files changed

+29
-17
lines changed
Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,31 @@
11

22
import os
33
import pathlib
4+
5+
from typing import Union
6+
47
from cryptography.hazmat.primitives import serialization
5-
from synlink.crypto.typing import KeyPair, PrivateKey
8+
from cryptography.hazmat.primitives.asymmetric import (
9+
ed25519 as ED25519,
10+
)
11+
12+
import synlink.crypto.ed25519 as ed25519
13+
from synlink.crypto.typing import PrivateKey, KeyPair
14+
15+
616

717
from typing import Optional
818

919
HOME_DIR : str = pathlib.Path.home().__str__()
1020
SSH_DEFAULT_DIRECTORY = os.path.join(HOME_DIR, ".ssh")
1121

12-
def load_ssh_keys(ssh_dir: str = SSH_DEFAULT_DIRECTORY, key_name: str = "id_ed25519", password : Optional[str] = None) -> KeyPair:
13-
"""Load SSH key pair from filesystem.
22+
def load_ssh_private_key(
23+
ssh_dir: Union[str, os.PathLike] = SSH_DEFAULT_DIRECTORY,
24+
key_name: str = "id_ed25519",
25+
password : Optional[str] = None,
26+
) -> KeyPair:
27+
"""Load private key from OpenSSL custom encoding, and reconstruct
28+
key pair.
1429
1530
Args:
1631
ssh_dir: Path to SSH directory (default: ~/.ssh)
@@ -22,14 +37,11 @@ def load_ssh_keys(ssh_dir: str = SSH_DEFAULT_DIRECTORY, key_name: str = "id_ed25
2237
Raises:
2338
FileNotFoundError: If key files don't exist
2439
ValueError: If keys are malformed or incompatible
25-
40+
NotImplemented: If other then ed25519
2641
Example:
2742
>>> keypair = load_ssh_keys(key_name="id_ed25519")
2843
"""
29-
file = os.path.join(ssh_dir, key_name),
30-
if not os.path.isfile(file):
31-
raise FileNotFoundError(f"{file} does not exist.")
32-
44+
file = os.path.join(ssh_dir, key_name)
3345
with open(
3446
file,
3547
"rb",
@@ -38,12 +50,12 @@ def load_ssh_keys(ssh_dir: str = SSH_DEFAULT_DIRECTORY, key_name: str = "id_ed25
3850
reader.read(-1),
3951
password=password,
4052
)
41-
42-
43-
seceret : PrivateKey = PrivateKey.from_bytes(
44-
buffer.private_bytes_raw()
45-
)
46-
47-
public = seceret.get_public_key()
48-
return KeyPair(seceret=seceret, public=public)
4953

54+
if isinstance(buffer, ED25519.Ed25519PrivateKey):
55+
secret = ed25519.PrivateKey.from_bytes(
56+
buffer.private_bytes_raw()
57+
)
58+
public = secret.get_public_key()
59+
return ed25519.KeyPair(secret=secret, public=public)
60+
else:
61+
raise NotImplemented

binding/python/py/synlink/crypto/typing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def to_bytes(self) -> bytes:
2929

3030
@classmethod
3131
@abstractmethod
32-
def from_bytes(cls) -> Self:
32+
def from_bytes(cls, data : bytes) -> Self:
3333
"""Return instance of the class from bytes."""
3434
...
3535

0 commit comments

Comments
 (0)