| 49 | } |
| 50 | |
| 51 | func (c *Context) GenerateSSHKey(keyName string, passphrase string) (*KeyPair, error) { |
| 52 | keygenExe, err := c.findKeygen() |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | |
| 57 | sshDir, err := c.SshDir() |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | |
| 62 | err = os.MkdirAll(sshDir, 0700) |
| 63 | if err != nil { |
| 64 | return nil, fmt.Errorf("could not create .ssh directory: %w", err) |
| 65 | } |
| 66 | |
| 67 | keyFile := filepath.Join(sshDir, keyName) |
| 68 | keyPair := KeyPair{ |
| 69 | PublicKeyPath: keyFile + ".pub", |
| 70 | PrivateKeyPath: keyFile, |
| 71 | } |
| 72 | |
| 73 | if _, err := os.Stat(keyFile); err == nil { |
| 74 | // Still return keyPair because the caller might be OK with this - they can check the error with errors.Is(err, ErrKeyAlreadyExists) |
| 75 | return &keyPair, ErrKeyAlreadyExists |
| 76 | } |
| 77 | |
| 78 | if err := os.MkdirAll(filepath.Dir(keyFile), 0711); err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | |
| 82 | keygenCmd := exec.Command(keygenExe, "-t", "ed25519", "-C", "", "-N", passphrase, "-f", keyFile) |
| 83 | err = run.PrepareCmd(keygenCmd).Run() |
| 84 | if err != nil { |
| 85 | return nil, err |
| 86 | } |
| 87 | |
| 88 | return &keyPair, nil |
| 89 | } |
| 90 | |
| 91 | func (c *Context) SshDir() (string, error) { |
| 92 | if c.configDir != "" { |