x509

package
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 1, 2023 License: Apache-2.0 Imports: 46 Imported by: 81

Documentation

Overview

Copyright 2021 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Package x509 parses X.509-encoded keys and certificates.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")

ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.

View Source
var ErrorIncorrectPassword = errors.New("x509: decryption password incorrect")

ErrorIncorrectPassword is returned when an incorrect password is detected.

Functions

func CertificateRequestText

func CertificateRequestText(csr *CertificateRequest) (string, error)

CertificateRequestText returns a human-readable string representation of the certificate request csr. The format is similar (but not identical) to the OpenSSL way of printing certificates.

func CertificateText

func CertificateText(cert *Certificate) (string, error)

CertificateText returns a human-readable string representation of the certificate cert. The format is similar (but not identical) to the OpenSSL way of printing certificates.

func Convert2CryptoHash

func Convert2CryptoHash(h Hash) (crypto.Hash, error)

func CreateCertificate

func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) ([]byte, error)

CreateCertificate 根据证书模板生成gmx509证书(v3)的DER字节数组

  • template : 证书模板
  • parent : 父证书(自签名时与template传入相同参数即可)
  • pub : 证书拥有者的公钥
  • priv : 签名者的私钥(有父证书的话,就是父证书拥有者的私钥)

当父证书中含有公钥时,必须确保签名者私钥中的公钥与其一致。

CreateCertificate creates a new X.509 v3 certificate based on a template. The following members of template are currently used:

  • AuthorityKeyId
  • BasicConstraintsValid
  • CRLDistributionPoints
  • DNSNames
  • EmailAddresses
  • ExcludedDNSDomains
  • ExcludedEmailAddresses
  • ExcludedIPRanges
  • ExcludedURIDomains
  • ExtKeyUsage
  • ExtraExtensions
  • IPAddresses
  • IsCA
  • IssuingCertificateURL
  • KeyUsage
  • MaxPathLen
  • MaxPathLenZero
  • NotAfter
  • NotBefore
  • OCSPServer
  • PermittedDNSDomains
  • PermittedDNSDomainsCritical
  • PermittedEmailAddresses
  • PermittedIPRanges
  • PermittedURIDomains
  • PolicyIdentifiers
  • SerialNumber
  • SignatureAlgorithm
  • Subject
  • SubjectKeyId
  • URIs
  • UnknownExtKeyUsage

The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the certificate to be generated and priv is the private key of the signer.

The returned slice is the certificate in DER encoding.

The currently supported key types are *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. pub must be a supported key type, and priv must be a crypto.Signer with a supported public key.

The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.

If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId will be generated from the hash of the public key.

func CreateCertificateRequest

func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error)

CreateCertificateRequest 基于证书申请模板生成一个新的证书申请。 注意,证书申请内部的公钥信息就是签名者的公钥,即,证书申请是申请者自签名的。

  • rand : 随机数获取用
  • template : 证书申请模板
  • priv : 申请者私钥

CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:

  • SignatureAlgorithm
  • Subject
  • DNSNames
  • EmailAddresses
  • IPAddresses
  • URIs
  • ExtraExtensions
  • Attributes (deprecated)

priv is the private key to sign the CSR with, and the corresponding public key will be included in the CSR. It must implement crypto.Signer and its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)

The returned slice is the certificate request in DER encoding.

func CreateCertificateRequestToPem

func CreateCertificateRequestToPem(template *CertificateRequest, signer interface{}) ([]byte, error)

CreateCertificateRequestToPem 创建证书申请并转为pem字节数组

@param template
@param signer
@return []byte
@return error

func CreateCertificateRequestToPemFile

func CreateCertificateRequestToPemFile(FileName string, template *CertificateRequest, signer interface{}) (bool, error)

CreateCertificateRequestToPemFile 创建证书申请并转为pem文件

@param FileName
@param template
@param signer
@return bool
@return error

func CreateCertificateToPem

func CreateCertificateToPem(template, parent *Certificate, pubKey, signer interface{}) ([]byte, error)

CreateCertificateToPem 创建gmx509证书并转为pem字节数组

@param template
@param parent
@param pubKey
@param signer
@return []byte
@return error

func CreateCertificateToPemFile

func CreateCertificateToPemFile(FileName string, template, parent *Certificate, pubKey, privKey interface{}) (bool, error)

CreateCertificateToPemFile 创建gmx509证书并转为pem文件

@param FileName
@param template
@param parent
@param pubKey
@param privKey
@return bool
@return error

func CreateEllipticSKI

func CreateEllipticSKI(curve elliptic.Curve, x, y *big.Int) []byte

CreateEllipticSKI 根据椭圆曲线公钥参数生成其SKI值

@param curve
@param x
@param y
@return []byte

func CreateRevocationList

func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)

CreateRevocationList creates a new X.509 v2 Certificate Revocation List, according to RFC 5280, based on template.

The CRL is signed by priv which should be the private key associated with the public key in the issuer certificate.

The issuer may not be nil, and the crlSign bit must be set in KeyUsage in order to use it as a CRL issuer.

The issuer distinguished name CRL field and authority key identifier extension are populated using the issuer certificate. issuer must have SubjectKeyId set.

func DecryptPEMBlock

func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)

DecryptPEMBlock takes a PEM block encrypted according to RFC 1423 and the password used to encrypt it and returns a slice of decrypted DER encoded bytes. It inspects the DEK-Info header to determine the algorithm used for decryption. If no DEK-Info header is present, an error is returned. If an incorrect password is detected an ErrorIncorrectPassword is returned. Because of deficiencies in the format, it's not always possible to detect an incorrect password. In these cases no error will be returned but the decrypted DER bytes will be random noise.

func EncryptPEMBlock

func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)

EncryptPEMBlock returns a PEM block of the specified type holding the given DER encoded data encrypted with the specified algorithm and password according to RFC 1423.

func GetRandBigInt

func GetRandBigInt() *big.Int

GetRandBigInt 随机生成序列号

@return *big.Int

func IsEncryptedPEMBlock

func IsEncryptedPEMBlock(b *pem.Block) bool

IsEncryptedPEMBlock returns whether the PEM block is password encrypted according to RFC 1423.

func MarshalECPrivateKey

func MarshalECPrivateKey(key interface{}) ([]byte, error)

MarshalECPrivateKey 将EC(椭圆曲线)私钥转为SEC 1, ASN.1 DER格式字节数组 私钥目前支持: *sm2.PrivateKey, *ecdsa.PrivateKey

MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY". For a more flexible key format which is not EC specific, use MarshalPKCS8PrivateKey.

func MarshalPKCS1PrivateKey

func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte

MarshalPKCS1PrivateKey 将RSA私钥转为PKCS #1, ASN.1 DER格式字节数组 MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY". For a more flexible key format which is not RSA specific, use MarshalPKCS8PrivateKey.

func MarshalPKCS1PublicKey

func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte

MarshalPKCS1PublicKey 将RSA公钥转为PKCS #1, ASN.1 DER字节数组 MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".

func MarshalPKCS8PrivateKey

func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error)

MarshalPKCS8PrivateKey 将私钥转为PKCS #8, ASN.1 DER字节数组

  • 私钥支持: sm2, ecdsa, ed25519, rsa

MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.

The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey and ed25519.PrivateKey. Unsupported key types result in an error.

This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

func MarshalPKIXPublicKey

func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)

MarshalPKIXPublicKey 将公钥转为PKIX, ASN.1 DER格式字节数组。 公钥支持 *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey , 这些公钥的pem类型是"PUBLIC KEY"。

MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. Unsupported key types result in an error.

This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

func ParseCRL

func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)

ParseCRL 将给定的字节数组(PEM/DER)转为CRL。 ParseCRL parses a CRL from the given bytes. It's often the case that PEM encoded CRLs will appear where they should be DER encoded, so this function will transparently handle PEM encoding as long as there isn't any leading garbage.

func ParseDERCRL

func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)

ParseDERCRL 将DER字节数组转为CRL。 ParseDERCRL parses a DER encoded CRL from the given bytes.

func ParseECPrivateKey

func ParseECPrivateKey(der []byte) (interface{}, error)

ParseECPrivateKey 将SEC 1, ASN.1 DER格式字节数组转为EC(椭圆曲线)私钥 私钥目前支持: *sm2.PrivateKey, *ecdsa.PrivateKey

ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form. This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".

func ParseGmx509DerToX509

func ParseGmx509DerToX509(asn1data []byte) (*x509.Certificate, error)

ParseGmx509DerToX509 将gmx509证书DER字节数组转为x509证书

@param asn1data
@return *x509.Certificate
@return error

func ParsePKCS1PrivateKey

func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)

ParsePKCS1PrivateKey 将PKCS #1, ASN.1 DER格式字节数组转为RSA私钥 ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".

func ParsePKCS1PublicKey

func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)

ParsePKCS1PublicKey 将PKCS #1, ASN.1 DER字节数组转为RSA公钥 ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.

This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error)

ParsePKCS8PrivateKey 将未加密的PKCS #8, ASN.1 DER格式字节数组转为对应的私钥。

  • 私钥支持: sm2, ecdsa, ed25519, rsa

ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.

It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, or a ed25519.PrivateKey. More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".

func ParsePKIXPublicKey

func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)

ParsePKIXPublicKey 将一个PKIX, ASN.1 DER格式字节数组转为对应的公钥。 公钥支持 *sm2.PublicKey, *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey , 这些公钥的pem类型是"PUBLIC KEY"。

ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).

It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey. More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

Example
package main

import (
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/rsa"
	"encoding/pem"
	"fmt"

	"github.com/hxx258456/ccgo/x509"
)

func main() {
	const pubPEM = `
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
-----END PUBLIC KEY-----`

	block, _ := pem.Decode([]byte(pubPEM))
	if block == nil {
		panic("failed to parse PEM block containing the public key")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		panic("failed to parse DER encoded public key: " + err.Error())
	}

	switch pub := pub.(type) {
	case *rsa.PublicKey:
		fmt.Println("pub is of type RSA:", pub)
	// case *dsa.PublicKey:
	// 	fmt.Println("pub is of type DSA:", pub)
	case *ecdsa.PublicKey:
		fmt.Println("pub is of type ECDSA:", pub)
	case ed25519.PublicKey:
		fmt.Println("pub is of type Ed25519:", pub)
	default:
		panic("unknown type of public key")
	}
}
Output:

func ReadPrivateKeyFromPem

func ReadPrivateKeyFromPem(privateKeyPem []byte, pwd []byte) (interface{}, error)

ReadPrivateKeyFromPem 将pem字节数组转为对应私钥

  • 私钥类型: *sm2.PrivateKey, *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey @param privateKeyPem 私钥pem字节数组 @param pwd pem解密口令 @return interface{} 返回私钥 @return error

func ReadPrivateKeyFromPemFile

func ReadPrivateKeyFromPemFile(FileName string, pwd []byte) (interface{}, error)

ReadPrivateKeyFromPemFile 将pem文件转为对应私钥

  • 私钥类型: *sm2.PrivateKey, *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey @param FileName pem文件路径 @param pwd pem解密口令 @return interface{} 返回私钥 @return error

func ReadPublicKeyFromPem

func ReadPublicKeyFromPem(publicKeyPem []byte) (interface{}, error)

ReadPublicKeyFromPem 将pem字节数组转为对应公钥

  • 公钥类型: *sm2.PublicKey, *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey @param publicKeyPem @return interface{} @return error

func ReadPublicKeyFromPemFile

func ReadPublicKeyFromPemFile(FileName string) (interface{}, error)

ReadPublicKeyFromPemFile 将pem文件转为对应公钥

  • 公钥类型: *sm2.PublicKey, *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey @param FileName @return interface{} @return error

func RegisterHash

func RegisterHash(h Hash, f func() hash.Hash)

RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.

func WritePrivateKeyToPem

func WritePrivateKeyToPem(key interface{}, pwd []byte) ([]byte, error)

WritePrivateKeyToPem 将私钥转为pem字节数组

  • 私钥类型: *sm2.PrivateKey, *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey @param key 私钥 @param pwd pem加密口令 @return []byte 私钥pem字节数组 @return error

func WritePrivateKeytoPemFile

func WritePrivateKeytoPemFile(FileName string, key interface{}, pwd []byte) (bool, error)

WritePrivateKeytoPemFile 将私钥转为pem文件

  • 私钥类型: *sm2.PrivateKey, *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey @param FileName pem文件路径 @param key 私钥 @param pwd pem加密口令 @return bool 成功与否 @return error

func WritePublicKeyToPem

func WritePublicKeyToPem(key interface{}) ([]byte, error)

WritePublicKeyToPem 将公钥转为pem字节数组

  • 公钥类型: *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey

    @param key @return []byte @return error

func WritePublicKeytoPemFile

func WritePublicKeytoPemFile(FileName string, key interface{}) (bool, error)

WritePublicKeytoPemFile 将公钥转为pem文件

  • 公钥类型: *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey

    @param FileName @param key @return bool @return error

Types

type CertPool

type CertPool struct {
	// contains filtered or unexported fields
}

CertPool is a set of certificates.

func NewCertPool

func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

func SystemCertPool

func SystemCertPool() (*CertPool, error)

SystemCertPool returns a copy of the system cert pool.

On Unix systems other than macOS the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively. The latter can be a colon-separated list.

Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.

New changes in the system cert pool might not be reflected in subsequent calls.

func (*CertPool) AddCert

func (s *CertPool) AddCert(cert *Certificate)

AddCert adds a certificate to a pool.

func (*CertPool) AppendCertsFromPEM

func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)

AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.

On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.

func (*CertPool) Subjects

func (s *CertPool) Subjects() [][]byte

Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.

type Certificate

type Certificate struct {
	// 完整的 ASN1 DER 证书字节数组(证书+签名算法+签名)
	// Complete ASN.1 DER content (certificate, signature algorithm and signature).
	Raw []byte
	// 签名内容的原始 ASN.1 DER字节数组
	// Certificate part of raw ASN.1 DER content.
	RawTBSCertificate []byte
	// SubjectPublicKeyInfo的DER字节数组
	// DER encoded SubjectPublicKeyInfo.
	RawSubjectPublicKeyInfo []byte
	// 证书拥有者的DER字节数组
	// DER encoded Subject
	RawSubject []byte
	// 证书签署者的DER字节数组
	// DER encoded Issuer
	RawIssuer []byte

	// 签名DER字节数组
	Signature []byte
	// 签名算法
	SignatureAlgorithm SignatureAlgorithm

	// 证书拥有者的公钥算法
	PublicKeyAlgorithm PublicKeyAlgorithm
	// 证书拥有者的公钥(证书的核心内容)
	PublicKey interface{}

	// 证书版本
	Version int
	// 证书序列号
	SerialNumber *big.Int
	// 证书签署者(提供私钥对RawTBSCertificate进行签名)
	Issuer pkix.Name
	// 证书拥有者(该证书的核心公钥的拥有者)
	Subject pkix.Name
	// 证书有效期间
	// Validity bounds.
	NotBefore, NotAfter time.Time
	// 证书公钥的用途
	KeyUsage KeyUsage

	// Extensions contains raw X.509 extensions. When parsing certificates,
	// this can be used to extract non-critical extensions that are not
	// parsed by this package. When marshaling certificates, the Extensions
	// field is ignored, see ExtraExtensions.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any
	// marshaled certificates. Values override any extensions that would
	// otherwise be produced based on the other fields. The ExtraExtensions
	// field is not populated when parsing certificates, see Extensions.
	ExtraExtensions []pkix.Extension

	// UnhandledCriticalExtensions contains a list of extension IDs that
	// were not (fully) processed when parsing. Verify will fail if this
	// slice is non-empty, unless verification is delegated to an OS
	// library which understands all the critical extensions.
	//
	// Users can access these extensions using Extensions and can remove
	// elements from this slice if they believe that they have been
	// handled.
	UnhandledCriticalExtensions []asn1.ObjectIdentifier

	// 公钥扩展用途
	// Sequence of extended key usages.
	ExtKeyUsage []ExtKeyUsage
	// 未知的公钥扩展用途
	// Encountered extended key usages unknown to this package.
	UnknownExtKeyUsage []asn1.ObjectIdentifier

	// 基础约束是否有效,控制 IsCA 与 MaxPathLen 是否有效
	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
	// and MaxPathLenZero are valid.
	BasicConstraintsValid bool
	// IsCA为false时,表示该证书不是CA证书,MaxPathLen无效。
	// IsCA为true时,表示该证书是CA证书,此时MaxPathLen表示该证书所属证书信任链中的中间CA证书的数量上限。
	IsCA bool

	// MaxPathLen and MaxPathLenZero indicate the presence and
	// value of the BasicConstraints' "pathLenConstraint".
	//
	// When parsing a certificate, a positive non-zero MaxPathLen
	// means that the field was specified, -1 means it was unset,
	// and MaxPathLenZero being true mean that the field was
	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
	// should be treated equivalent to -1 (unset).
	//
	// When generating a certificate, an unset pathLenConstraint
	// can be requested with either MaxPathLen == -1 or using the
	// zero value for both MaxPathLen and MaxPathLenZero.
	MaxPathLen int
	// MaxPathLenZero indicates that BasicConstraintsValid==true
	// and MaxPathLen==0 should be interpreted as an actual
	// maximum path length of zero. Otherwise, that combination is
	// interpreted as MaxPathLen not being set.
	MaxPathLenZero bool

	// 证书拥有者密钥ID
	// 以sm2公钥为例,计算方式为 将椭圆曲线上的公钥座标转换为字节数组再做sm3散列
	SubjectKeyId []byte
	// 证书签署者密钥ID(自签名时,AuthorityKeyId就是自己的SubjectKeyId;由父证书签名时,就是父证书的SubjectKeyId)
	AuthorityKeyId []byte

	// RFC 5280, 4.2.2.1 (Authority Information Access)
	OCSPServer            []string
	IssuingCertificateURL []string

	// Subject Alternate Name values. (Note that these values may not be valid
	// if invalid values were contained within a parsed certificate. For
	// example, an element of DNSNames may not be a valid DNS domain name.)
	// go1.15开始废弃CommonName,使用SAN扩展信息。
	// SAN扩展信息由下面四个字段组成。
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL

	// Name constraints
	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
	PermittedDNSDomains         []string
	ExcludedDNSDomains          []string
	PermittedIPRanges           []*net.IPNet
	ExcludedIPRanges            []*net.IPNet
	PermittedEmailAddresses     []string
	ExcludedEmailAddresses      []string
	PermittedURIDomains         []string
	ExcludedURIDomains          []string

	// CRL Distribution Points
	CRLDistributionPoints []string

	PolicyIdentifiers []asn1.ObjectIdentifier
}

Certificate gmx509证书结构体 A Certificate represents an X.509 certificate.

func ParseCertificate

func ParseCertificate(der []byte) (*Certificate, error)

ParseCertificate 将DER字节数组转为gmx509证书 ParseCertificate parses a single certificate from the given ASN.1 DER data.

func ParseCertificates

func ParseCertificates(der []byte) ([]*Certificate, error)

ParseCertificates 将DER字节数组转为多个gmx509证书 ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.

func ReadCertificateFromPem

func ReadCertificateFromPem(certPem []byte) (*Certificate, error)

ReadCertificateFromPem 将pem字节数组转为gmx509证书

@param certPem
@return *Certificate
@return error

func ReadCertificateFromPemFile

func ReadCertificateFromPemFile(FileName string) (*Certificate, error)

ReadCertificateFromPemFile 将pem文件转为gmx509证书

@param FileName
@return *Certificate
@return error

func (*Certificate) CheckCRLSignature

func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error

CheckCRLSignature 检查证书撤销列表CRL是否由c签名。 CheckCRLSignature checks that the signature in crl is from c.

func (*Certificate) CheckSignature

func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error

CheckSignature 使用c的公钥检查签名是否有效

  • algo : 签名算法
  • signed : 签名内容
  • signature : 签名DER字节数组

CheckSignature verifies that signature is a valid signature over signed from c's public key.

func (*Certificate) CheckSignatureFrom

func (c *Certificate) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom 检查对c做的签名是否是父证书拥有者的有效签名(使用父证书中的公钥验签) CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

func (*Certificate) CreateCRL

func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)

CreateCRL 创建一个CRL

  • priv : 撤销证书列表的签署者私钥
  • revokedCerts : 撤销证书列表

CreateCRL returns a DER encoded CRL, signed by this Certificate, that contains the given list of revoked certificates.

Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL. To generate a standards compliant CRL, use CreateRevocationList instead.

func (*Certificate) Equal

func (c *Certificate) Equal(other *Certificate) bool

func (*Certificate) FromX509Certificate

func (c *Certificate) FromX509Certificate(x509Cert *x509.Certificate)

FromX509Certificate x509转gmx509

func (*Certificate) ToX509Certificate

func (c *Certificate) ToX509Certificate() *x509.Certificate

ToX509Certificate gmx509转x509

func (*Certificate) Verify

func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)

Verify 尝试构建证书c的有效信任链。 成功时将返回验证成功的证书链,其中第一个证书即c自身,最后一个是opts.Roots中的某个根证书。 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.

opts.Roots为空时,将使用系统平台的根证书验证。此时验证的详细信息与本方法的实现会有不同。 如果系统根证书不可用将返回SystemRootsError。 If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.

信任链的中间证书的名称约束对整个信任链有效,不能只看传入的opts.DNSName。 Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn't permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.

名称约束遵循RFC 5280标准,因此可以使用前导句点匹配。 Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.

Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)

WARNING: this function doesn't do any revocation checking.

Example
package main

import (
	"encoding/pem"

	"github.com/hxx258456/ccgo/x509"
)

func main() {
	// Verifying with a custom list of root certificates.

	const rootPEM = `
-----BEGIN CERTIFICATE-----
MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
-----END CERTIFICATE-----`

	const certPEM = `
-----BEGIN CERTIFICATE-----
MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
-----END CERTIFICATE-----`

	// First, create the set of root certificates. For this example we only
	// have one. It's also possible to omit this in order to use the
	// default root set of the current operating system.
	roots := x509.NewCertPool()
	ok := roots.AppendCertsFromPEM([]byte(rootPEM))
	if !ok {
		panic("failed to parse root certificate")
	}

	block, _ := pem.Decode([]byte(certPEM))
	if block == nil {
		panic("failed to parse certificate PEM")
	}
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		panic("failed to parse certificate: " + err.Error())
	}

	opts := x509.VerifyOptions{
		DNSName: "mail.google.com",
		Roots:   roots,
	}

	if _, err := cert.Verify(opts); err != nil {
		panic("failed to verify certificate: " + err.Error())
	}
}
Output:

func (*Certificate) VerifyHostname

func (c *Certificate) VerifyHostname(h string) error

VerifyHostname 检查证书域名(或IP) VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.

IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the left-most label.

Note that the legacy Common Name field is ignored.

type CertificateInvalidError

type CertificateInvalidError struct {
	Cert   *Certificate
	Reason InvalidReason
	Detail string
}

CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.

func (CertificateInvalidError) Error

func (e CertificateInvalidError) Error() string

type CertificateRequest

type CertificateRequest struct {
	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
	RawSubject               []byte // DER encoded Subject.

	Version            int
	Signature          []byte
	SignatureAlgorithm SignatureAlgorithm

	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          interface{}

	Subject pkix.Name

	// Attributes contains the CSR attributes that can parse as
	// pkix.AttributeTypeAndValueSET.
	//
	// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
	// generating the requestedExtensions attribute.
	Attributes []pkix.AttributeTypeAndValueSET

	// Extensions contains all requested extensions, in raw form. When parsing
	// CSRs, this can be used to extract extensions that are not parsed by this
	// package.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any CSR
	// marshaled by CreateCertificateRequest. Values override any extensions
	// that would otherwise be produced based on the other fields but are
	// overridden by any extensions specified in Attributes.
	//
	// The ExtraExtensions field is not populated by ParseCertificateRequest,
	// see Extensions instead.
	ExtraExtensions []pkix.Extension

	// Subject Alternate Name values.
	// go1.15开始废弃CommonName,使用SAN扩展信息。
	// SAN扩展信息由下面四个字段组成。
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL
}

CertificateRequest 证书申请 CertificateRequest represents a PKCS #10, certificate signature request.

func ParseCertificateRequest

func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)

ParseCertificateRequest 将DER字节数组转为单个证书申请。 ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.

func ReadCertificateRequestFromPem

func ReadCertificateRequestFromPem(certPem []byte) (*CertificateRequest, error)

ReadCertificateRequestFromPem 将pem字节数组转为证书申请

@param certPem
@return *CertificateRequest
@return error

func ReadCertificateRequestFromPemFile

func ReadCertificateRequestFromPemFile(FileName string) (*CertificateRequest, error)

ReadCertificateRequestFromPemFile 将pem文件转为证书申请

@param FileName
@return *CertificateRequest
@return error

func (*CertificateRequest) CheckSignature

func (c *CertificateRequest) CheckSignature() error

CheckSignature 检查证书申请c的签名是否有效 CheckSignature reports whether the signature on c is valid.

type ConstraintViolationError

type ConstraintViolationError struct{}

ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn't a certificate signing key.

func (ConstraintViolationError) Error

type ExtKeyUsage

type ExtKeyUsage int

ExtKeyUsage 公钥(证书)扩展用途 ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.

const (
	ExtKeyUsageAny                        ExtKeyUsage = iota // Any Extended Key Usage
	ExtKeyUsageServerAuth                                    // TLS Web Server Authentication
	ExtKeyUsageClientAuth                                    // TLS Web Client Authentication
	ExtKeyUsageCodeSigning                                   // Code Signing
	ExtKeyUsageEmailProtection                               // E-mail Protection
	ExtKeyUsageIPSECEndSystem                                // IPSec End System
	ExtKeyUsageIPSECTunnel                                   // IPSec Tunnel
	ExtKeyUsageIPSECUser                                     // IPSec User
	ExtKeyUsageTimeStamping                                  // Time Stamping
	ExtKeyUsageOCSPSigning                                   // OCSP Signing
	ExtKeyUsageMicrosoftServerGatedCrypto                    // Microsoft Server Gated Crypto
	ExtKeyUsageNetscapeServerGatedCrypto                     // Netscape Server Gated Crypto
	ExtKeyUsageMicrosoftCommercialCodeSigning
	ExtKeyUsageMicrosoftKernelCodeSigning
)

type Hash

type Hash uint

Hash 重写Hash相关定义,用来代替`crypto.Hash` Hash identifies a cryptographic hash function that is implemented in another package.

const (
	MD4         Hash = 1 + iota // import golang.org/x/crypto/md4
	MD5                         // import crypto/md5
	SHA1                        // import crypto/sha1
	SHA224                      // import crypto/sha256
	SHA256                      // import crypto/sha256
	SHA384                      // import crypto/sha512
	SHA512                      // import crypto/sha512
	MD5SHA1                     // no implementation; MD5+SHA1 used for TLS RSA
	RIPEMD160                   // import golang.org/x/crypto/ripemd160
	SHA3_224                    // import golang.org/x/crypto/sha3
	SHA3_256                    // import golang.org/x/crypto/sha3
	SHA3_384                    // import golang.org/x/crypto/sha3
	SHA3_512                    // import golang.org/x/crypto/sha3
	SHA512_224                  // import crypto/sha512
	SHA512_256                  // import crypto/sha512
	BLAKE2s_256                 // import golang.org/x/crypto/blake2s
	BLAKE2b_256                 // import golang.org/x/crypto/blake2b
	BLAKE2b_384                 // import golang.org/x/crypto/blake2b
	BLAKE2b_512                 // import golang.org/x/crypto/blake2b
	SM3                         // 添加sm3

)

func (Hash) Available

func (h Hash) Available() bool

Available reports whether the given hash function is linked into the binary.

func (Hash) HashFunc

func (h Hash) HashFunc() crypto.Hash

HashFunc simply returns the value of h so that Hash implements SignerOpts.

func (Hash) New

func (h Hash) New() hash.Hash

New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.

func (Hash) Size

func (h Hash) Size() int

Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn't require that the hash function in question be linked into the program.

func (Hash) String

func (h Hash) String() string

type HostnameError

type HostnameError struct {
	Certificate *Certificate
	Host        string
}

HostnameError results when the set of authorized names doesn't match the requested name.

func (HostnameError) Error

func (h HostnameError) Error() string

type InsecureAlgorithmError

type InsecureAlgorithmError SignatureAlgorithm

An InsecureAlgorithmError

func (InsecureAlgorithmError) Error

func (e InsecureAlgorithmError) Error() string

type InvalidReason

type InvalidReason int
const (
	// NotAuthorizedToSign results when a certificate is signed by another
	// which isn't marked as a CA certificate.
	NotAuthorizedToSign InvalidReason = iota
	// Expired results when a certificate has expired, based on the time
	// given in the VerifyOptions.
	Expired
	// CANotAuthorizedForThisName results when an intermediate or root
	// certificate has a name constraint which doesn't permit a DNS or
	// other name (including IP address) in the leaf certificate.
	CANotAuthorizedForThisName
	// TooManyIntermediates results when a path length constraint is
	// violated.
	TooManyIntermediates
	// IncompatibleUsage results when the certificate's key usage indicates
	// that it may only be used for a different purpose.
	IncompatibleUsage
	// NameMismatch results when the subject name of a parent certificate
	// does not match the issuer name in the child.
	NameMismatch
	// NameConstraintsWithoutSANs is a legacy error and is no longer returned.
	NameConstraintsWithoutSANs
	// UnconstrainedName results when a CA certificate contains permitted
	// name constraints, but leaf certificate contains a name of an
	// unsupported or unconstrained type.
	UnconstrainedName
	// TooManyConstraints results when the number of comparison operations
	// needed to check a certificate exceeds the limit set by
	// VerifyOptions.MaxConstraintComparisions. This limit exists to
	// prevent pathological certificates can consuming excessive amounts of
	// CPU time to verify.
	TooManyConstraints
	// CANotAuthorizedForExtKeyUsage results when an intermediate or root
	// certificate does not permit a requested extended key usage.
	CANotAuthorizedForExtKeyUsage
)

type KeyUsage

type KeyUsage int

KeyUsage 公钥用途,即证书用途。 KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.

const (
	KeyUsageDigitalSignature  KeyUsage = 1 << iota // Digital Signature
	KeyUsageContentCommitment                      // Non Repudiation
	KeyUsageKeyEncipherment                        // Key Encipherment
	KeyUsageDataEncipherment                       // Data Encipherment
	KeyUsageKeyAgreement                           // Key Agreement
	KeyUsageCertSign                               // Certificate Sign
	KeyUsageCRLSign                                // CRL Sign
	KeyUsageEncipherOnly                           // Encipher Only
	KeyUsageDecipherOnly                           // Decipher Only
)

type PEMCipher

type PEMCipher int
const (
	PEMCipherDES PEMCipher
	PEMCipher3DES
	PEMCipherAES128
	PEMCipherAES192
	PEMCipherAES256
	PEMCipherSM4
)

Possible values for the EncryptPEMBlock encryption algorithm.

type PublicKeyAlgorithm

type PublicKeyAlgorithm int

PublicKeyAlgorithm 公钥算法

const (
	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
	RSA
	DSA // Unsupported.
	ECDSA
	Ed25519
	SM2 // 公钥算法添加SM2
)

func (PublicKeyAlgorithm) String

func (algo PublicKeyAlgorithm) String() string

type RevocationList

type RevocationList struct {
	// SignatureAlgorithm is used to determine the signature algorithm to be
	// used when signing the CRL. If 0 the default algorithm for the signing
	// key will be used.
	SignatureAlgorithm SignatureAlgorithm

	// RevokedCertificates is used to populate the revokedCertificates
	// sequence in the CRL, it may be empty. RevokedCertificates may be nil,
	// in which case an empty CRL will be created.
	RevokedCertificates []pkix.RevokedCertificate

	// Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
	// which should be a monotonically increasing sequence number for a given
	// CRL scope and CRL issuer.
	Number *big.Int
	// ThisUpdate is used to populate the thisUpdate field in the CRL, which
	// indicates the issuance date of the CRL.
	ThisUpdate time.Time
	// NextUpdate is used to populate the nextUpdate field in the CRL, which
	// indicates the date by which the next CRL will be issued. NextUpdate
	// must be greater than ThisUpdate.
	NextUpdate time.Time
	// ExtraExtensions contains any additional extensions to add directly to
	// the CRL.
	ExtraExtensions []pkix.Extension
}

RevocationList contains the fields used to create an X.509 v2 Certificate Revocation list with CreateRevocationList.

type SignatureAlgorithm

type SignatureAlgorithm int

SignatureAlgorithm 签名算法

const (
	UnknownSignatureAlgorithm SignatureAlgorithm = iota

	MD2WithRSA // Unsupported.
	MD5WithRSA // Only supported for signing, not verification.
	SHA1WithRSA
	SHA256WithRSA
	SHA384WithRSA
	SHA512WithRSA
	DSAWithSHA1   // Unsupported.
	DSAWithSHA256 // Unsupported.
	ECDSAWithSHA1
	ECDSAWithSHA256
	ECDSAWithSHA384
	ECDSAWithSHA512
	SHA256WithRSAPSS
	SHA384WithRSAPSS
	SHA512WithRSAPSS
	PureEd25519
	SM2WithSM3 // 签名算法添加国密算法: SM2WithSM3
)

func (SignatureAlgorithm) String

func (algo SignatureAlgorithm) String() string

type SystemRootsError

type SystemRootsError struct {
	Err error
}

SystemRootsError results when we fail to load the system root certificates.

func (SystemRootsError) Error

func (se SystemRootsError) Error() string

func (SystemRootsError) Unwrap

func (se SystemRootsError) Unwrap() error

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct{}

func (UnhandledCriticalExtension) Error

type UnknownAuthorityError

type UnknownAuthorityError struct {
	Cert *Certificate
	// contains filtered or unexported fields
}

UnknownAuthorityError results when the certificate issuer is unknown

func (UnknownAuthorityError) Error

func (e UnknownAuthorityError) Error() string

type VerifyOptions

type VerifyOptions struct {
	// 如果设置了 DNSName,则使用 Certificate.VerifyHostname 或平台验证程序检查叶证书。
	// DNSName, if set, is checked against the leaf certificate with
	// Certificate.VerifyHostname or the platform verifier.
	DNSName string

	// 可选的中间证书池,它们不是信任锚,但可用于形成从叶证书到根证书的链。
	// Intermediates is an optional pool of certificates that are not trust
	// anchors, but can be used to form a chain from the leaf certificate to a
	// root certificate.
	Intermediates *CertPool

	// 根是叶证书需要链接到的一组受信任的根证书。 如果为零,则使用系统根或平台验证程序。
	// Roots is the set of trusted root certificates the leaf certificate needs
	// to chain up to. If nil, the system roots or the platform verifier are used.
	Roots *CertPool

	// CurrentTime 用于检查链中所有证书的有效性。 如果为零,则使用当前时间。
	// CurrentTime is used to check the validity of all certificates in the
	// chain. If zero, the current time is used.
	CurrentTime time.Time

	// KeyUsages 指定允许的扩展公钥用途。
	// 目标证书只要匹配上任意一个指定的用途即可通过该项检查。
	// 该字段默认值为 ExtKeyUsageServerAuth。
	// 如果允许任意一种扩展公钥用途,请在该字段列表中加入 ExtKeyUsageAny。
	// KeyUsages specifies which Extended Key Usage values are acceptable. A
	// chain is accepted if it allows any of the listed values. An empty list
	// means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny.
	KeyUsages []ExtKeyUsage

	// MaxConstraintComparisions 是检查给定证书的名称约束时要执行的最大比较次数。
	// 如果为零,则使用合理的默认值。
	// 此限制可防止病态证书在验证时消耗过多的 CPU 时间。 它不适用于平台验证者。
	// MaxConstraintComparisions is the maximum number of comparisons to
	// perform when checking a given certificate's name constraints. If
	// zero, a sensible default is used. This limit prevents pathological
	// certificates from consuming excessive amounts of CPU time when
	// validating. It does not apply to the platform verifier.
	MaxConstraintComparisions int
}

VerifyOptions contains parameters for Certificate.Verify.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL