upaas/internal/ssh/keygen.go
clawbot fb91246b07 chore: code cleanup and best practices (closes #45)
- Fix gofmt formatting across 4 files
- Add nolint annotations with justifications for all gosec findings
- Resolve all 7 pre-existing linter warnings
- make check now passes cleanly
2026-02-19 20:27:07 -08:00

54 lines
1.4 KiB
Go

// Package ssh provides SSH key generation utilities.
package ssh
import (
"crypto/ed25519"
"crypto/rand"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ssh"
)
// KeyPair contains an SSH key pair.
type KeyPair struct {
PrivateKey string //nolint:gosec // field name describes SSH key material, not a hardcoded secret
PublicKey string
}
// GenerateKeyPair generates a new Ed25519 SSH key pair.
func GenerateKeyPair() (*KeyPair, error) {
// Generate Ed25519 key pair
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, fmt.Errorf("failed to generate key pair: %w", err)
}
// Convert private key to PEM format
privateKeyPEM, err := ssh.MarshalPrivateKey(privateKey, "")
if err != nil {
return nil, fmt.Errorf("failed to marshal private key: %w", err)
}
// Convert public key to authorized_keys format
sshPublicKey, err := ssh.NewPublicKey(publicKey)
if err != nil {
return nil, fmt.Errorf("failed to create SSH public key: %w", err)
}
return &KeyPair{
PrivateKey: string(pem.EncodeToMemory(privateKeyPEM)),
PublicKey: string(ssh.MarshalAuthorizedKey(sshPublicKey)),
}, nil
}
// ValidatePrivateKey validates that a private key is valid.
func ValidatePrivateKey(privateKeyPEM string) error {
_, err := ssh.ParsePrivateKey([]byte(privateKeyPEM))
if err != nil {
return fmt.Errorf("invalid private key: %w", err)
}
return nil
}