|
| 1 | +package sshkey |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto" |
| 5 | + "crypto/ed25519" |
| 6 | + "encoding/pem" |
| 7 | + "fmt" |
| 8 | + |
| 9 | + "golang.org/x/crypto/ssh" |
| 10 | +) |
| 11 | + |
| 12 | +// GenerateKeyPair generates a new ed25519 ssh key pair, and returns the private key and |
| 13 | +// the public key respectively. |
| 14 | +func GenerateKeyPair() ([]byte, []byte, error) { |
| 15 | + pub, priv, err := ed25519.GenerateKey(nil) |
| 16 | + if err != nil { |
| 17 | + return nil, nil, fmt.Errorf("could not generate key pair: %w", err) |
| 18 | + } |
| 19 | + |
| 20 | + privBytes, err := encodePrivateKey(priv) |
| 21 | + if err != nil { |
| 22 | + return nil, nil, fmt.Errorf("could not encode private key: %w", err) |
| 23 | + } |
| 24 | + |
| 25 | + pubBytes, err := encodePublicKey(pub) |
| 26 | + if err != nil { |
| 27 | + return nil, nil, fmt.Errorf("could not encode public key: %w", err) |
| 28 | + } |
| 29 | + |
| 30 | + return privBytes, pubBytes, nil |
| 31 | +} |
| 32 | + |
| 33 | +func encodePrivateKey(priv crypto.PrivateKey) ([]byte, error) { |
| 34 | + privPem, err := ssh.MarshalPrivateKey(priv, "") |
| 35 | + if err != nil { |
| 36 | + return nil, err |
| 37 | + } |
| 38 | + |
| 39 | + return pem.EncodeToMemory(privPem), nil |
| 40 | +} |
| 41 | + |
| 42 | +func encodePublicKey(pub crypto.PublicKey) ([]byte, error) { |
| 43 | + sshPub, err := ssh.NewPublicKey(pub) |
| 44 | + if err != nil { |
| 45 | + return nil, err |
| 46 | + } |
| 47 | + |
| 48 | + return ssh.MarshalAuthorizedKey(sshPub), nil |
| 49 | +} |
| 50 | + |
| 51 | +type privateKeyWithPublicKey interface { |
| 52 | + crypto.PrivateKey |
| 53 | + Public() crypto.PublicKey |
| 54 | +} |
| 55 | + |
| 56 | +// GeneratePublicKey generate a public key from the provided private key. |
| 57 | +func GeneratePublicKey(privBytes []byte) ([]byte, error) { |
| 58 | + priv, err := ssh.ParseRawPrivateKey(privBytes) |
| 59 | + if err != nil { |
| 60 | + return nil, fmt.Errorf("could not decode private key: %w", err) |
| 61 | + } |
| 62 | + |
| 63 | + key, ok := priv.(privateKeyWithPublicKey) |
| 64 | + if !ok { |
| 65 | + return nil, fmt.Errorf("private key doesn't export Public() crypto.PublicKey") |
| 66 | + } |
| 67 | + |
| 68 | + pubBytes, err := encodePublicKey(key.Public()) |
| 69 | + if err != nil { |
| 70 | + return nil, fmt.Errorf("could not encode public key: %w", err) |
| 71 | + } |
| 72 | + |
| 73 | + return pubBytes, nil |
| 74 | +} |
| 75 | + |
| 76 | +// GetPublicKeyFingerprint generate the finger print for the provided public key. |
| 77 | +func GetPublicKeyFingerprint(pubBytes []byte) (string, error) { |
| 78 | + pub, _, _, _, err := ssh.ParseAuthorizedKey(pubBytes) |
| 79 | + if err != nil { |
| 80 | + return "", fmt.Errorf("could not decode public key: %w", err) |
| 81 | + } |
| 82 | + |
| 83 | + fingerprint := ssh.FingerprintLegacyMD5(pub) |
| 84 | + |
| 85 | + return fingerprint, nil |
| 86 | +} |
0 commit comments