使用 Go 生成 X509 證書

代碼摘取自 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()

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容