golang x509的Certificate.Verify函数

周末在家无趣,研究了一个golang里面的Certificate.Verify函数。

golang的官方定义在这里:https://golang.org/pkg/crypto/x509/#Certificate.Verify

函数原型声明如下:
func (c Certificate) Verify(opts VerifyOptions) (chains [][]Certificate, err error)

其中:

  1. c *Certificate是待验证的证书
  2. 参数opts定义如下,我们只关注这两个成员。
type VerifyOptions struct {
    ...
    Roots         *CertPool  // if nil, the system roots are used
    Intermediates *CertPool
    ...
}
  1. 返回值是一个二维数组证书。

这个函数的功能是:

Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.

If opts.Roots is nil and system roots are unavailable the returned error will be of type SystemRootsError.

解释一下就是:

  1. 试图找出所有从c开始到opts.Roots中的证书为止的所有的证书链。
  2. 这其中会有多条证书链,所以返回类型是二维数组[][]*Certificate,每一条链都是一个一维数组表示。
  3. 对每一条链:
    • 第一个元素都是c
    • 最后一个元素是opts.Roots中的成员。
    • 中间元素都是opts.Intermediates中的成员。中间元素可能没有,则此条证书链只包含两个成员c和opts.Roots成员。
  4. 如果opts.Roots为空,那么opts.Roots使用系统根证书。

举一个例子:
假设存在证书链签出关系:C1 -> C2 -> C3 -> C4,即C1签出C2,C2签出C3,C3签出C4;现在使用函数:

C4.Verify(VerifyOptions {
  Roots        : [...],
  Intermediates: [...],
})

我们根据Intermediates和Roots的值不同,比较输出结果:

Roots Intermediates 输出 说明
[C1, C2, C3] [] [C4, C3]
[] [C1, C2, C3] error 找不到Roots,又不属于系统根证书
[C3] [C1, C2, C3] [C4, C3] 这个C3就是Roots中的C3
[C1, C2, C3] [C3] [C4, C3]
[C4, C3, C2]
第一个C3是Roots.C3
第二个C3是Intermediates.C3
[C1, C2, C3] [C1, C2, C3] [C4, C3]
[C4, C3, C2]
[C4, C3, C2, C1]
C4 -> C3.R
C4 -> C3.I -> C2.R
C4 -> C3.I -> C2.I -> C1.R
... ... ... ...

你可能感兴趣的:(golang x509的Certificate.Verify函数)