From 8d80e760657463eda55e2f0c773ed3fe3b3e3b08 Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Tue, 11 Apr 2023 11:39:10 -0400 Subject: [PATCH] feat: return ssh.Signer --- keygen.go | 11 +++++++---- keygen_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/keygen.go b/keygen.go index 5603205..0f091ed 100644 --- a/keygen.go +++ b/keygen.go @@ -218,12 +218,15 @@ func (s *SSHKeyPair) PrivateKey() crypto.PrivateKey { } } +// Signer returns an ssh.Signer for the key pair. +func (s *SSHKeyPair) Signer() ssh.Signer { + sk, _ := ssh.NewSignerFromKey(s.PrivateKey()) + return sk +} + // PublicKey returns the ssh.PublicKey for the key pair. func (s *SSHKeyPair) PublicKey() ssh.PublicKey { - p, err := ssh.NewPublicKey(s.cryptoPublicKey()) - if err != nil { - return nil - } + p, _ := ssh.NewPublicKey(s.cryptoPublicKey()) return p } diff --git a/keygen_test.go b/keygen_test.go index 5762cfe..c56b27c 100644 --- a/keygen_test.go +++ b/keygen_test.go @@ -3,6 +3,7 @@ package keygen import ( "bytes" "crypto/elliptic" + "fmt" "io/ioutil" "os" "path/filepath" @@ -19,6 +20,38 @@ func TestNewSSHKeyPair(t *testing.T) { } } +func TestNilSSHKeyPair(t *testing.T) { + for _, kt := range []KeyType{RSA, Ed25519, ECDSA} { + t.Run(fmt.Sprintf("test nil key pair for %s", kt), func(t *testing.T) { + kp, err := New("", WithKeyType(kt)) + if err != nil { + t.Errorf("error creating SSH key pair: %v", err) + } + if kp == nil { + t.Error("expected key pair to be non-nil") + } + if kp.PrivateKey() == nil { + t.Error("expected private key to be non-nil") + } + if kp.PublicKey() == nil { + t.Error("expected public key to be non-nil") + } + if kp.RawPrivateKey() == nil { + t.Error("expected raw private key to be non-nil") + } + if kp.RawProtectedPrivateKey() == nil { + t.Error("expected raw protected private key to be non-nil") + } + if kp.AuthorizedKey() == "" { + t.Error("expected authorized key to be non-nil") + } + if kp.Signer() == nil { + t.Error("expected signer to be non-nil") + } + }) + } +} + func TestGenerateEd25519Keys(t *testing.T) { // Create temp directory for keys dir := t.TempDir()