Search code examples
gosshssh-keygen

How to avoid "passphrase is too short" from golang


What I am doing is to create a ssh key from a golang program, using

exec.Command("ssh-keygen", "-f", "id_rsa", "-t", "rsa", "-P", "\"\"")

but the output fails

exit status 1: Saving key "id_rsa" failed: passphrase is too short (minimum five characters)

If I execute the command in the terminal it works perfect.

Generating public/private rsa key pair.
Your identification has been saved in id_rsa.
Your public key has been saved in id_rsa.pub.
The key fingerprint is:
SHA256:HYixKOtEB42jAr+XNa9uQMZnvmLHa6Sirq+ietWaxzI [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|  .o  .          |
|. o... + .       |
|.oooo o . .      |
|o..++ =  . .     |
|. o+ B oS .      |
| o. = + .        |
|  .o O o         |
|. o E X          |
|%*.o Xo.         |
+----[SHA256]-----+

The complete code is:

package main

import (
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ssh-keygen", "-f", "id_rsa", "-t", "rsa", "-P", "\"\"")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Result: " + out.String())
}

Solution

  • You don't need to specify an empty -P attribute, just simply use:

    exec.Command("ssh-keygen", "-f", "id_rsa", "-t", "rsa")
    

    If for any reason you need to specify empty -P

    exec.Command("ssh-keygen", "-f", "id_rsa", "-t", "rsa", "-P", "")
    

    Also before creating the id_rsa file make sure it doesn't exist in the directory you are creating it, otherwise you will get exit error 1: