X.509数字证书标准

X.509 数字证书结构图

简单来说,数字证书就是一张附带了数字签名的信息表。

x509结构

以RSA算法为例

X.509证书和私钥生成

生成秘钥流程

  1. 使用crypto/rsa中的GenerateKey(random io.Reader, bits int)方法生成私钥(结构体)
  2. 因为X509证书采用了ASN1描述结构,需要通过Go语言API将的到的私钥(结构体),转换为BER编码规则的字符串。
  3. 需要将ASN1 BER 规则转回为PEM数据编码。pem.Encode(out io.Writer, b *Block)
  4. 将返回的数据保存

生成证书流程

  1. 使用crypto/rsa中的GenerateKey(random io.Reader, bits int)方法生成私钥(结构体)
  2. 构建x.509的证书的结构模型template
  3. 根据公钥、私钥、证书模板生成DER编码规则的字符串。
  4. 需要生成的DER编码转回为PEM数据编码。pem.Encode(out io.Writer, b *Block)
  5. 将返回的数据保存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func TestX509Gen(t *testing.T) {
max := new(big.Int).Lsh(big.NewInt(1),128) //把 1 左移 128 位,返回给 big.Int
serialNumber, _ := rand.Int(rand.Reader, max) //返回在 [0, max) 区间均匀随机分布的一个随机值
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 颁布的唯一序列号,在此使用一个大随机数来代表它
Subject: subject,
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 *time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, //KeyUsage 与 ExtKeyUsage 用来表明该证书是用来做服务器认证的
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, // 密钥扩展用途的序列
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}
pk, _ := rsa.GenerateKey(rand.Reader, 2048) //生成一对具有指定字位数的RSA密钥

//CreateCertificate基于模板创建一个新的证书
//第二个第三个参数相同,则证书是自签名的
//返回的切片是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()
}

X.509证书解析验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func TestX509CertRead(t *testing.T) {
// Decode the certificate
file, _ := ioutil.ReadFile("cert.pem")
certBlock, _ := pem.Decode(file)
cert, _ := x509.ParseCertificate(certBlock.Bytes)
// 解析内容
fmt.Println(cert.Version)
fmt.Println(cert.Subject.CommonName)

// 验证签名
err := cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
if err == nil{
println("succeed")
}else {
println("failed")
}

println(cert.PublicKey.(*rsa.PublicKey).N.String())
}

X.509证书解析私钥

1
2
3
4
5
6
7
8
9
10
11
func TestSKRead(t *testing.T) {
readFile, _ := ioutil.ReadFile("key.pem")
pemBlock, _ := pem.Decode(readFile)

privateStream, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
if err != nil {
return
}

println(privateStream.PublicKey.N.String())
}

参考:

百度百科