go语言中使用crypto/x509创建证书及使用crypto/rsa创建私钥/公钥
go语言也可以生成x509证书和等效的RSA私钥/公钥,下面使用crypto/x509创建证书和crypto/rsa包来创建私钥/公钥
示例代码:
package main
import (
"time"
"os"
"encoding/gob"
"encoding/pem"
"math/big"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io/ioutil"
"crypto/rsa"
"crypto/rand"
)
func main() {
// 好的,让我们用一些数据填充证书
// 并非证书中的所有字段都会被填充
// 参见证书结构
// http://golang.org/pkg/crypto/x509/#Certificate
template := &x509.Certificate {
IsCA : true,
BasicConstraintsValid : true,
SubjectKeyId : []byte{1,2,3},
SerialNumber : big.NewInt(1234),
Subject : pkix.Name{
Country : []string{"Earth"},
Organization: []string{"Mother Nature"},
},
NotBefore : time.Now(),
NotAfter : time.Now().AddDate(5,5,5),
// see http://golang.org/pkg/crypto/x509/#KeyUsage
ExtKeyUsage : []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage : x509.KeyUsageDigitalSignature|x509.KeyUsageCertSign,
}
//生成私钥
privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Println(err)
}
publickey := &privatekey.PublicKey
//创建自签名证书。 模板 = 父级
var parent = template
cert, err := x509.CreateCertificate(rand.Reader, template, parent, publickey,privatekey)
if err != nil {
fmt.Println(err)
}
//保存私钥
pkey := x509.MarshalPKCS1PrivateKey(privatekey)
ioutil.WriteFile("private.key", pkey, 0777)
fmt.Println("私钥保存到 private.key")
//保存公钥
pubkey, _ := x509.MarshalPKIXPublicKey(publickey)
ioutil.WriteFile("public.key", pubkey, 0777)
fmt.Println("公钥保存到 public.key")
//保存证书
ioutil.WriteFile("cert.pem", cert, 0777)
fmt.Println("证书保存到 cert.pem")
//这些是使用 encoding/gob 样式保存的文件
privkeyfile, _ := os.Create("privategob.key")
privkeyencoder := gob.NewEncoder(privkeyfile)
privkeyencoder.Encode(privatekey)
privkeyfile.Close()
pubkeyfile, _ := os.Create("publickgob.key")
pubkeyencoder := gob.NewEncoder(pubkeyfile)
pubkeyencoder.Encode(publickey)
pubkeyfile.Close()
//这将创建纯文本 PEM 文件。
pemfile, _ := os.Create("certpem.pem")
var pemkey = &pem.Block{
Type : "RSA PRIVATE KEY",
Bytes : x509.MarshalPKCS1PrivateKey(privatekey)}
pem.Encode(pemfile, pemkey)
pemfile.Close()
}
相关文章