Adapted from https://stackoverflow.com/a/34347463/943814 MakeSSHKeyPair make a pair of public and private keys for SSH access. Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file. Private Key generated is PEM encoded
()
| 222 | // Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file. |
| 223 | // Private Key generated is PEM encoded |
| 224 | func MakeSSHKeyPair() (string, string, error) { |
| 225 | privateKey, err := rsa.GenerateKey(rand.Reader, 1024) |
| 226 | if err != nil { |
| 227 | return "", "", err |
| 228 | } |
| 229 | |
| 230 | // generate and write private key as PEM |
| 231 | var privKeyBuf strings.Builder |
| 232 | |
| 233 | privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} |
| 234 | if err := pem.Encode(&privKeyBuf, privateKeyPEM); err != nil { |
| 235 | return "", "", err |
| 236 | } |
| 237 | |
| 238 | // generate and write public key |
| 239 | pub, err := ssh.NewPublicKey(&privateKey.PublicKey) |
| 240 | if err != nil { |
| 241 | return "", "", err |
| 242 | } |
| 243 | |
| 244 | pubKey := string(ssh.MarshalAuthorizedKey(pub)) |
| 245 | |
| 246 | return pubKey, privKeyBuf.String(), nil |
| 247 | } |