Skip to content

Instantly share code, notes, and snippets.

@kwoktung
Created October 17, 2019 01:39
Show Gist options
  • Save kwoktung/86d66660238e845fe92cdce763020f6c to your computer and use it in GitHub Desktop.
Save kwoktung/86d66660238e845fe92cdce763020f6c to your computer and use it in GitHub Desktop.
generate openssh key pair by golang
/*
* Genarate rsa keys.
*/
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ssh"
)
func main() {
reader := rand.Reader
bitSize := 2048
key, _ := rsa.GenerateKey(reader, bitSize)
publicKey, _ := ssh.NewPublicKey(&key.PublicKey)
fmt.Println(publicKey.Type())
data := publicKey.Marshal()
encodeString := base64.StdEncoding.EncodeToString(data)
fmt.Println(encodeString) // ssh-rsa form
block := &pem.Block{
Type: "OPENSSH PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
dd := pem.EncodeToMemory(block)
fmt.Println(string(dd)) // PKCS #1 ANS.1 form
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment