Search code examples
goopensslx509certificatex509

Create key and certificate in golang same as openssl do for local host


How can I code in Go the equivalent of the following openssl command?

openssl req -subj /C=/ST=/O=/L=/CN=localhost/OU=/ -x509 -nodes -days 3650  \
            -newkey rsa:4096 -keyout test.key -out test.crt

The goal is to generate a new certificate from its certificate request.


Solution

  • Found my solution by this way-

    key, err := rsa.GenerateKey(rand.Reader, 4096)
        if err != nil {
            return "", "", err
        }
        keyBytes := x509.MarshalPKCS1PrivateKey(key)
        // PEM encoding of private key
        keyPEM := pem.EncodeToMemory(
            &pem.Block{
                Type:  "RSA PRIVATE KEY",
                Bytes: keyBytes,
            },
        )
        fmt.Println(string(keyPEM))
        
        notBefore := time.Now()
        notAfter := notBefore.Add(365*24*10*time.Hour)
    
        //Create certificate templet
        template := x509.Certificate{
            SerialNumber:          big.NewInt(0),
            Subject:               pkix.Name{CommonName: "localhost"},
            SignatureAlgorithm:    x509.SHA256WithRSA,
            NotBefore:             notBefore,
            NotAfter:              notAfter,
            BasicConstraintsValid: true,
            KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement | x509.KeyUsageKeyEncipherment | x509.KeyUsageDataEncipherment,
            ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
        }
        //Create certificate using templet
        derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
        if err != nil {
            return "", "", err
    
        }
        //pem encoding of certificate
        certPem := string(pem.EncodeToMemory(
            &pem.Block{
                Type:  "CERTIFICATE",
                Bytes: derBytes,
            },
        ))
        fmt.Println(certPem))