Skip to content

Commit

Permalink
Rename KeyPairExist -> IsKeyPairExists and add NewWithWrite
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Sep 13, 2021
1 parent 490b97f commit fa8424b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
23 changes: 18 additions & 5 deletions keygen.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,14 @@ func (s SSHKeyPair) publicKeyPath() string {
return filepath.Join(s.KeyDir, s.Filename+".pub")
}

// NewSSHKeyPair generates an SSHKeyPair, which contains a pair of SSH keys.
// The keys are written to disk.
func NewSSHKeyPair(path string, name string, passphrase []byte, keyType string) (*SSHKeyPair, error) {
// New generates an SSHKeyPair, which contains a pair of SSH keys.
func New(path, name string, passphrase []byte, keyType string) (*SSHKeyPair, error) {
var err error
s := &SSHKeyPair{
KeyDir: path,
Filename: fmt.Sprintf("%s_%s", name, keyType),
}
if s.KeyPairExist() {
if s.IsKeyPairExists() {
pubData, err := ioutil.ReadFile(s.publicKeyPath())
if err != nil {
return nil, err
Expand All @@ -101,6 +100,20 @@ func NewSSHKeyPair(path string, name string, passphrase []byte, keyType string)
return s, nil
}

// New generates an SSHKeyPair and writes it to disk if not exist.
func NewWithWrite(path, name string, passphrase []byte, keyType string) (*SSHKeyPair, error) {
s, err := New(path, name, passphrase, keyType)
if err != nil {
return nil, err
}
if !s.IsKeyPairExists() {
if err = s.WriteKeys(); err != nil {
return nil, err
}
}
return s, nil
}

// generateEd25519Keys creates a pair of EdD25519 keys for SSH auth.
func (s *SSHKeyPair) generateEd25519Keys() error {
// Generate keys
Expand Down Expand Up @@ -242,7 +255,7 @@ func (s *SSHKeyPair) WriteKeys() error {
return nil
}

func (s *SSHKeyPair) KeyPairExist() bool {
func (s *SSHKeyPair) IsKeyPairExists() bool {
return fileExists(s.privateKeyPath()) && fileExists(s.publicKeyPath())
}

Expand Down
8 changes: 1 addition & 7 deletions keygen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,10 @@ import (

func TestNewSSHKeyPair(t *testing.T) {
dir := t.TempDir()
k, err := NewSSHKeyPair(dir, "test", []byte(""), "rsa")
_, err := NewWithWrite(dir, "test", []byte(""), "rsa")
if err != nil {
t.Errorf("error creating SSH key pair: %v", err)
}
if !k.KeyPairExist() {
err = k.WriteKeys()
if err != nil {
t.Errorf("error writing SSH key pair: %v", err)
}
}
}

func TestGenerateEd25519Keys(t *testing.T) {
Expand Down

0 comments on commit fa8424b

Please sign in to comment.