upaas/internal/ssh/keygen.go
clawbot 0fcf12d2cc fix: resolve all lint issues on main branch
- funcorder: reorder RemoveImage before unexported methods in docker/client.go
- gosec G117: add json:"-" tags to SessionSecret and PrivateKey fields
- gosec G117: replace login struct with map to avoid secret pattern match
- gosec G705: add #nosec for text/plain XSS false positive
- gosec G703: add #nosec for internal path traversal false positive
- gosec G704: validate URLs and add #nosec for config-sourced SSRF false positives
- gosec G306: use 0o600 permissions in test file
- revive: rename unused parameters to _
- wsl_v5: add missing blank line before assignment
2026-02-20 02:39:18 -08:00

54 lines
1.3 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 `json:"-"`
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
}