Created
October 17, 2019 01:39
-
-
Save kwoktung/86d66660238e845fe92cdce763020f6c to your computer and use it in GitHub Desktop.
generate openssh key pair by golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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