"""Ed25519 key at /.gpu-rent/id_ed25519 (no passphrase).""" from __future__ import annotations from pathlib import Path from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from gpu_rent.paths import default_ssh_key_path def public_path(private: Path) -> Path: return private.with_suffix(private.suffix + ".pub") if private.suffix else Path(str(private) + ".pub") def ensure_ed25519(path: Path | None = None) -> tuple[Path, Path]: private = path or default_ssh_key_path() pub = public_path(private) if private.is_file() and pub.is_file(): return private, pub private.parent.mkdir(parents=True, exist_ok=True) key = Ed25519PrivateKey.generate() private_bytes = key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.OpenSSH, encryption_algorithm=serialization.NoEncryption(), ) public_bytes = key.public_key().public_bytes( encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH, ) + b" gpu-rent\n" private.write_bytes(private_bytes) try: private.chmod(0o600) except OSError: pass pub.write_bytes(public_bytes) return private, pub def key_ready(path: Path | None = None) -> bool: private = path or default_ssh_key_path() return private.is_file() and public_path(private).is_file()