Skip to content

Instantly share code, notes, and snippets.

@NHAS
Last active May 2, 2023 12:47
Show Gist options
  • Save NHAS/cad2e0063e78e6893902f6bd7c991ee6 to your computer and use it in GitHub Desktop.
Save NHAS/cad2e0063e78e6893902f6bd7c991ee6 to your computer and use it in GitHub Desktop.
Generate SSH private key (Ed25519)
package main
import (
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"golang.org/x/crypto/ssh"
)
func generateSSHPrivateKey() (sshPriv ssh.Signer, err error) {
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return sshPriv, err
}
bytes, err := x509.MarshalPKCS8PrivateKey(priv) // Convert a generated ed25519 key into a PEM block so that the ssh library can ingest it, bit round about tbh
if err != nil {
return sshPriv, err
}
privatePem := pem.EncodeToMemory(
&pem.Block{
Type: "PRIVATE KEY",
Bytes: bytes,
},
)
sshPriv, err = ssh.ParsePrivateKey(privatePem)
if err != nil {
return sshPriv, err
}
return sshPriv, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment