Last active
February 27, 2022 08:44
-
-
Save NHAS/3634599eb5f664cdf65979fe8639dc35 to your computer and use it in GitHub Desktop.
Golang generate SSH certificate
This file contains 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
package main | |
import ( | |
"crypto/ed25519" | |
"crypto/rand" | |
"crypto/x509" | |
"encoding/base64" | |
"encoding/pem" | |
"fmt" | |
"log" | |
"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 | |
} | |
func check(err error) { | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func main() { | |
CA, err := generateSSHPrivateKey() | |
check(err) | |
child, err := generateSSHPrivateKey() | |
check(err) | |
// Create a cert and sign it for use in tests. | |
testCert := &ssh.Certificate{ | |
CertType: ssh.UserCert, | |
Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil | |
ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage | |
ValidAfter: 0, // unix epoch | |
ValidBefore: ssh.CertTimeInfinity, // The end of currently representable time. | |
Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil | |
Key: child.PublicKey(), | |
KeyId: "testcert", | |
SignatureKey: CA.PublicKey(), | |
Permissions: ssh.Permissions{ | |
CriticalOptions: map[string]string{}, | |
Extensions: map[string]string{}, | |
}, | |
} | |
err = testCert.SignCert(rand.Reader, CA) | |
check(err) | |
fmt.Printf("%s %s\n", testCert.Type(), base64.StdEncoding.EncodeToString(testCert.Marshal())) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment