Sling Academy
Home/Golang/Creating Self-Signed Certificates in Go

Creating Self-Signed Certificates in Go

Last updated: November 27, 2024

In modern web development, SSL/TLS certificates are crucial in ensuring that data is securely transmitted over networks. In some cases, especially during development, you might need a self-signed certificate instead of acquiring one from a certificate authority (CA). In this article, we'll walk through creating self-signed certificates using Go. This guide includes step-by-step instructions along with the corresponding code examples.

Introduction to SSL/TLS Certificates

SSL/TLS certificates are digital certificates that provide authentication for a website and enable an encrypted connection. Self-signed certificates, as the name suggests, are signed by the individual user rather than a trusted certificate authority. While these can be great for development and internal systems, they should not be used in production environments where trust is essential.

Generating a Self-Signed Certificate in Go

Let's get started with generating a self-signed certificate using Go's crypto/tls and crypto/x509 libraries.

Step 1: Set Up Your Project

Create a new directory for your project and initialize a Go module:

mkdir ssl-cert-generator
cd ssl-cert-generator
go mod init ssl-cert-generator

Step 2: Write the Code to Generate a Certificate

Create a new file named main.go and add the following code:

package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "math/big"
    "os"
    "time"
)

func main() {
    priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    if err != nil {
        panic(err)
    }

    notBefore := time.Now()
    notAfter := notBefore.Add(365 * 24 * time.Hour)

    serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
    if err != nil {
        panic(err)
    }

    template := x509.Certificate{
        SerialNumber: serialNumber,
        Subject: pkix.Name{
            Organization: []string{"My Organization"},
        },
        NotBefore:             notBefore,
        NotAfter:              notAfter,
        KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
        BasicConstraintsValid: true,
    }

    derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
    if err != nil {
        panic(err)
    }

    certOut, err := os.Create("cert.pem")
    if err != nil {
        panic(err)
    }
    pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
    certOut.Close()

    keyOut, err := os.Create("key.pem")
    if err != nil {
        panic(err)
    }
    pem.Encode(keyOut, pemBlockForKey(priv))
    keyOut.Close()
}

func pemBlockForKey(priv *ecdsa.PrivateKey) *pem.Block {
    b, err := x509.MarshalECPrivateKey(priv)
    if err != nil {
        panic(err)
    }
    return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
}

Step 3: Run Your Program

Compile and run your Go program to generate your self-signed certificate and private key:

go run main.go

This will create two files, cert.pem and key.pem, in your project directory. These files represent your self-signed certificate and its corresponding private key.

Conclusion

In this article, we demonstrated how to create a self-signed SSL/TLS certificate using Go. Such certificates are essential in testing environments or internal applications where a trusted CA-signed certificate isn't necessary. Although self-signed certificates suffice for these purposes, they're not suitable for public-facing production environments due to trust issues. Happy coding!

Next Article: Understanding and Using the `crypto/rsa` Package for Encryption in Go

Previous Article: TLS in Go: Setting Up Secure Client-Server Communication

Series: Cryptography and Security in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant