You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Go实现与openssl生成localhost证书命令等效的代码

Go语言实现等效openssl自签本地证书功能

需要实现的目标openssl命令如下:

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

上述命令的核心作用是生成无加密的4096位RSA私钥,以及有效期10年的localhost自签证书,两份文件分别输出为test.key和test.crt。

完整Go实现代码

package main

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

func main() {
	// 1. 生成4096位RSA私钥,对应原命令 -newkey rsa:4096 -nodes 参数
	privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
	if err != nil {
		panic(err)
	}

	// 私钥序列化为PEM格式写入test.key,无加密
	keyFile, err := os.Create("test.key")
	if err != nil {
		panic(err)
	}
	defer keyFile.Close()
	err = pem.Encode(keyFile, &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
	})
	if err != nil {
		panic(err)
	}

	// 2. 构造X509证书模板,对应原命令 -subj、-days 参数
	template := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName: "localhost", // 匹配原命令的CN=localhost,其余主体字段留空
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().AddDate(10, 0, 0), // 有效期10年即3650天
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA:                  true,
		DNSNames:              []string{"localhost"}, // 适配新版浏览器SAN字段校验要求,不影响原命令功能兼容性
	}

	// 3. 自签证书,对应原命令 -x509 参数
	certBytes, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
	if err != nil {
		panic(err)
	}

	// 证书序列化为PEM格式写入test.crt
	certFile, err := os.Create("test.crt")
	if err != nil {
		panic(err)
	}
	defer certFile.Close()
	err = pem.Encode(certFile, &pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	})
	if err != nil {
		panic(err)
	}
}

效果说明

  • 生成的私钥未加密,和原命令-nodes参数效果完全一致
  • 证书除补充了SAN字段的localhost(适配新版Chrome、Safari等浏览器对HTTPS证书的强制校验要求,原openssl命令生成的证书在新版浏览器会报SAN缺失错误),其余有效期、主体信息、密钥强度完全匹配原命令输出
  • 直接运行代码即可在当前目录生成test.key和test.crt,可直接用于本地localhost的HTTPS服务

内容的提问来源于stack exchange,提问作者psk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:06:03