golang动态生成自签名证书和证书颁发机构的测试插件库testcerts的使用

golang动态生成自签名证书和证书颁发机构的测试插件库testcerts的使用

testcerts是一个用于在测试中动态生成自签名证书和证书颁发机构的Golang库,可以避免在代码仓库中保存测试证书。

基本用法

func TestFunc(t *testing.T) {
    // 创建自签名证书和密钥并写入临时文件
    cert, key, err := testcerts.GenerateToTempFile("/tmp/")
    if err != nil {
        // 处理错误
    }
    defer os.Remove(key)
    defer os.Remove(cert)

    // 使用测试证书启动HTTP监听器
    err = http.ListenAndServeTLS("127.0.0.1:443", cert, key, someHandler)
    if err != nil {
        // 处理错误
    }
}

高级用法:创建证书颁发机构

对于更复杂的测试,可以使用该包创建证书颁发机构(CA),并为任何测试域创建由该CA签名的密钥对。

func TestFunc(t *testing.T) {
    // 生成证书颁发机构
    ca := testcerts.NewCA()

    go func() {
        // 为"localhost"创建签名的证书和密钥
        certs, err := ca.NewKeyPair("localhost")
        if err != nil {
            // 处理错误
        }

        // 将证书写入文件
        err = certs.ToFile("/tmp/cert", "/tmp/key")
        if err != nil {
            // 处理错误
        }

        // 启动HTTP监听器
        err = http.ListenAndServeTLS("localhost:443", "/tmp/cert", "/tmp/key", someHandler)
        if err != nil {
            // 处理错误
        }
    }()

    // 使用自签名CA创建客户端
    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: certs.ConfigureTLSConfig(ca.GenerateTLSConfig()),
        },
    }

    // 发起HTTPS请求
    r, _ := client.Get("https://localhost")
}

完整示例

下面是一个完整的测试示例,展示了如何使用testcerts创建CA并测试HTTPS服务:

package main

import (
    "net/http"
    "os"
    "testing"
    
    "github.com/madflojo/testcerts"
)

func TestHTTPS(t *testing.T) {
    // 1. 创建证书颁发机构
    ca := testcerts.NewCA()
    
    // 2. 为测试域名创建证书
    certs, err := ca.NewKeyPair("example.com")
    if err != nil {
        t.Fatalf("Failed to create key pair: %v", err)
    }
    
    // 3. 将证书写入临时文件
    certFile := "/tmp/test-cert.pem"
    keyFile := "/tmp/test-key.pem"
    defer os.Remove(certFile)
    defer os.Remove(keyFile)
    
    if err := certs.ToFile(certFile, keyFile); err != nil {
        t.Fatalf("Failed to write cert files: %v", err)
    }
    
    // 4. 启动测试HTTPS服务器
    go func() {
        mux := http.NewServeMux()
        mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            w.Write([]byte("Hello, TLS!"))
        })
        
        if err := http.ListenAndServeTLS(":8443", certFile, keyFile, mux); err != nil {
            t.Logf("Server error: %v", err)
        }
    }()
    
    // 5. 创建信任CA的HTTP客户端
    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: certs.ConfigureTLSConfig(ca.GenerateTLSConfig()),
        },
    }
    
    // 6. 测试HTTPS请求
    resp, err := client.Get("https://example.com:8443")
    if err != nil {
        t.Fatalf("HTTPS request failed: %v", err)
    }
    defer resp.Body.Close()
    
    // 验证响应
    if resp.StatusCode != http.StatusOK {
        t.Errorf("Expected status 200, got %d", resp.StatusCode)
    }
}

贡献

如果发现bug或有功能建议,请提交issue或pull request。

许可证

testcerts使用MIT许可证发布。


更多关于golang动态生成自签名证书和证书颁发机构的测试插件库testcerts的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang动态生成自签名证书和证书颁发机构的测试插件库testcerts的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang动态生成自签名证书和CA测试库testcerts使用指南

在开发和测试环境中,经常需要动态生成自签名证书和证书颁发机构(CA)。testcerts是一个方便的Go库,专门用于测试目的的自签名证书生成。

testcerts简介

testcerts是一个轻量级的Go库,主要用于:

  • 快速生成自签名证书
  • 创建测试用的证书颁发机构(CA)
  • 为测试环境提供TLS证书支持

安装testcerts

go get github.com/rancher/dynamiclistener/cert/testcerts

基本使用方法

1. 生成自签名证书

package main

import (
	"crypto/tls"
	"fmt"
	"github.com/rancher/dynamiclistener/cert/testcerts"
)

func main() {
	// 生成自签名证书
	cert, key, err := testcerts.GenerateSelfSignedCert("localhost", []string{"127.0.0.1"})
	if err != nil {
		panic(err)
	}

	// 创建TLS证书
	tlsCert, err := tls.X509KeyPair(cert, key)
	if err != nil {
		panic(err)
	}

	fmt.Println("Successfully generated self-signed certificate")
}

2. 创建CA并签发证书

package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"github.com/rancher/dynamiclistener/cert/testcerts"
)

func main() {
	// 生成CA证书和私钥
	caCert, caKey, err := testcerts.GenerateCACert()
	if err != nil {
		panic(err)
	}

	// 使用CA签发服务器证书
	serverCert, serverKey, err := testcerts.GenerateSignedCert("localhost", []string{"127.0.0.1"}, caCert, caKey)
	if err != nil {
		panic(err)
	}

	// 创建证书池并添加CA证书
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	// 配置TLS
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{
			{
				Certificate: [][]byte{serverCert},
				PrivateKey:  serverKey,
			},
		},
		RootCAs: caCertPool,
	}

	fmt.Println("Successfully generated CA and server certificate")
	_ = tlsConfig
}

高级用法

自定义证书有效期

package main

import (
	"time"
	"github.com/rancher/dynamiclistener/cert/testcerts"
)

func main() {
	// 设置证书有效期为10天
	testcerts.SetCertValidity(10 * 24 * time.Hour)
	
	// 然后正常生成证书...
}

生成客户端证书

package main

import (
	"github.com/rancher/dynamiclistener/cert/testcerts"
)

func main() {
	// 生成CA
	caCert, caKey, _ := testcerts.GenerateCACert()
	
	// 生成客户端证书
	clientCert, clientKey, err := testcerts.GenerateClientCert("test-client", caCert, caKey)
	if err != nil {
		panic(err)
	}
	
	// 使用clientCert和clientKey进行客户端认证...
}

实际应用示例

创建HTTPS测试服务器

package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"github.com/rancher/dynamiclistener/cert/testcerts"
)

func main() {
	// 生成自签名证书
	cert, key, err := testcerts.GenerateSelfSignedCert("localhost", []string{"127.0.0.1"})
	if err != nil {
		log.Fatal(err)
	}

	// 创建TLS配置
	tlsCert, err := tls.X509KeyPair(cert, key)
	if err != nil {
		log.Fatal(err)
	}

	server := &http.Server{
		Addr: ":8443",
		TLSConfig: &tls.Config{
			Certificates: []tls.Certificate{tlsCert},
		},
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, TLS!")
	})

	fmt.Println("Server starting on https://localhost:8443")
	log.Fatal(server.ListenAndServeTLS("", ""))
}

注意事项

  1. 仅用于测试环境:testcerts生成的证书不适合生产环境使用
  2. 证书安全性:自签名证书不会被公共CA信任,浏览器会显示安全警告
  3. 证书有效期:默认有效期较短,适合短期测试

testcerts库简化了测试环境中的证书管理,使得开发人员可以快速搭建安全的测试环境而无需复杂的证书配置流程。

回到顶部