代碼摘取自 Go Web Programming 相關(guān)部分
//證書生成
package main
import (
"math/big"
"crypto/rand"
"crypto/x509/pkix"
"crypto/x509"
"time"
"net"
"crypto/rsa"
"os"
"encoding/pem"
)
func main(){
max := new(big.Int).Lsh(big.NewInt(1),128) //把 1 左移 128 位,返回給 big.Int
serialNumber, _ := rand.Int(rand.Reader, max) //返回在 [0, max) 區(qū)間均勻隨機分布的一個隨機值
subject := pkix.Name{ //Name代表一個X.509識別名。只包含識別名的公共屬性,額外的屬性被忽略。
Organization: []string{"Manning Publications Co."},
OrganizationalUnit: []string{"Books"},
CommonName: "Go Web Programming",
}
template := x509.Certificate{
SerialNumber: serialNumber, // SerialNumber 是 CA 頒布的唯一序列號,在此使用一個大隨機數(shù)來代表它
Subject: subject,
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 *time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, //KeyUsage 與 ExtKeyUsage 用來表明該證書是用來做服務(wù)器認證的
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, // 密鑰擴展用途的序列
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}
pk, _ := rsa.GenerateKey(rand.Reader, 2048) //生成一對具有指定字位數(shù)的RSA密鑰
//CreateCertificate基于模板創(chuàng)建一個新的證書
//第二個第三個參數(shù)相同,則證書是自簽名的
//返回的切片是DER編碼的證書
derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &pk.PublicKey, pk) //DER 格式
certOut, _ := os.Create("cert.pem")
pem.Encode(certOut,&pem.Block{Type:"CERTIFICAET", Bytes: derBytes})
certOut.Close()
keyOut, _ := os.Create("key.pem")
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)})
keyOut.Close()
}