Golang crypto/x509.CreateCertificate function example

package crypto/x509

CreateCertificate creates a new certificate based on a template. The following members of template are used: SerialNumber, Subject, NotBefore, NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, PermittedDNSDomains, SignatureAlgorithm.

The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the signee and priv is the private key of the signer.

The returned slice is the certificate in DER encoding.

The only supported key types are RSA and ECDSA (*rsa.PublicKey or *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PrivateKey for priv).

Golang crypto/x509.CreateCertificate function usage example

 template := &x509.Certificate {
 IsCA : true,
 BasicConstraintsValid : true,
 SubjectKeyId : []byte{1,2,3},
 SerialNumber : big.NewInt(1234),
 Subject : pkix.Name{
 Country : []string{"Earth"},
 Organization: []string{"Mother Nature"},
 },
 NotBefore : time.Now(),
 NotAfter : time.Now().AddDate(5,5,5),
 // see http://golang.org/pkg/crypto/x509/#KeyUsage
 ExtKeyUsage : []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
 KeyUsage : x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign,
 }

 // generate private key
 privatekey, err := rsa.GenerateKey(rand.Reader, 2048)

 if err != nil {
 fmt.Println(err)
 }

 publickey := &privatekey.PublicKey

 // create a self-signed certificate. template = parent
 var parent = template
 cert, err := x509.CreateCertificate(rand.Reader, template, parent, publickey,privatekey)

 if err != nil {
 fmt.Println(err)
 }

See https://www.socketloop.com/tutorials/golang-create-x509-certificate-private-and-public-keys for full example

Reference :

http://golang.org/pkg/crypto/x509/#CreateCertificate

Advertisement