zer09
zer09

Reputation: 1586

golang, can i create X509KeyPair using rsa key?

I am trying to create gRPC connection with mutual tls following the instruction on this blog Secure gRPC with TLS/SSL, but i don't want to create the certificate and save it to a file on the disk, I want the service itself to create its keys, then the certificate authority key will be taken somewhere else (I am planning using the google pki as the ca).

What i did so far I can create the private/public key pair using rsa, then encode the public key to pem key following some code here Golang : Generate DSA private, public key and PEM files example now i am stock on how to create the certificate using the LoadX509KeyPair. I don't know where to get the value for the second parameter, it needs keyPemBlock in bytes, but the RSA private key is not on bytes.

I would like to ask, is there a much more better way to create a certificate using the RSA, if it is possible?

And also if we can create a certificate using RSA; using the incomplete solution of mine above, where i can get the value for the second parameter of the tls.LoadX509KeyPair?

Thank you

Upvotes: 1

Views: 4401

Answers (1)

Motakjuq
Motakjuq

Reputation: 2259

If you want to generate your own certificate and private key, you have to do:

1.- Generate private key:

key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
    log.Fatal("Private key cannot be created.", err.Error())
}

// Generate a pem block with the private key
keyPem := pem.EncodeToMemory(&pem.Block{
    Type:  "RSA PRIVATE KEY",
    Bytes: x509.MarshalPKCS1PrivateKey(key),
})

2.- Generate the certificate:

tml := x509.Certificate{
    // you can add any attr that you need
    NotBefore:    time.Now(),
    NotAfter:     time.Now().AddDate(5, 0, 0),
    // you have to generate a different serial number each execution
    SerialNumber: big.NewInt(123123),
    Subject: pkix.Name{
        CommonName:   "New Name",
        Organization: []string{"New Org."},
    },
    BasicConstraintsValid: true,
}
cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
if err != nil {
    log.Fatal("Certificate cannot be created.", err.Error())
}

// Generate a pem block with the certificate
certPem := pem.EncodeToMemory(&pem.Block{
    Type:  "CERTIFICATE",
    Bytes: cert,
})

3.- Load certificate/private key pair:

tlsCert, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
    log.Fatal("Cannot be loaded the certificate.", err.Error())
}

4.- Use the tlsCert for whatever you want, ex:

l, err := tls.Listen("tcp", ":8080", &tls.Config{
    Certificates: []tls.Certificate{tlsCert},
})

Upvotes: 10

Related Questions