crypto/x509
包提供了对X.509证书的编码和解码支持。X.509是最常见的证书格式,广泛用于SSL/TLS加密通信和其他安全通信。
以下是一些使用crypto/x509
包的常见方法:
- 解码证书:
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
"log"
)
func main() {
// 假设blockOfPEM是一个包含X.509证书的PEM块
block, _ := pem.Decode(blockOfPEM)
if block == nil {
log.Fatal("failed to decode PEM block containing certificate")
}
// 使用x509包解析证书
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
log.Fatal(err)
}
fmt.Println(cert)
}
- 验证证书链:
package main
import (
"crypto/x509"
"fmt"
"log"
)
func main() {
// 假设certs是一个包含证书链的切片
roots := x509.NewCertPool()
for _, cert := range certs {
roots.AddCert(cert)
}
opts := x509.VerifyOptions{
Roots: roots,
}
_, err := cert.Verify(opts)
if err != nil {
log.Fatal(err)
}
fmt.Println("The certificate is valid")
}
- 生成自签名证书:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"os"
"time"
)
func main() {
// 生成私钥
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
// 证书的主体信息
subj := pkix.Name{
CommonName: "example.com",
}
// 证书的有效期
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
log.Fatalf("failed to generate serial number: %s", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: subj,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
// 自签名
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
// 将证书写入文件
certOut, err := os.Create("cert.pem")
if err != nil {
log.Fatal(err)
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes}); err != nil {
log.Fatal(err)
}
cert