Documentation
¶
Overview ¶
crypto/x509 add sm2 support
Index ¶
- Constants
- Variables
- func Convert2CryptoHash(h Hash) (crypto.Hash, error)
- func CreateCertificate(template, parent *Certificate, publicKey interface{}, signer crypto.Signer) ([]byte, error)
- func CreateCertificateFromReader(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)
- func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, signer crypto.Signer) (csr []byte, err error)
- func CreateCertificateRequestToMem(template *CertificateRequest, privKey *sm2.PrivateKey) ([]byte, error)
- func CreateCertificateRequestToPem(template *CertificateRequest, signer crypto.Signer) ([]byte, error)
- func CreateCertificateRequestToPemFile(FileName string, template *CertificateRequest, privKey *sm2.PrivateKey) (bool, error)
- func CreateCertificateToMem(template, parent *Certificate, pubKey, privKey interface{}) ([]byte, error)
- func CreateCertificateToPem(template, parent *Certificate, pubKey *sm2.PublicKey, signer crypto.Signer) ([]byte, error)
- func CreateCertificateToPemFile(FileName string, template, parent *Certificate, pubKey, privKey interface{}) (bool, error)
- func CreateEllipticSKI(curve elliptic.Curve, x, y *big.Int) []byte
- func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, ...) ([]byte, error)
- func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
- func DegenerateCertificate(cert []byte) ([]byte, error)
- func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
- func GetRandBigInt() *big.Int
- func IsEncryptedPEMBlock(b *pem.Block) bool
- func MarshalECPrivateKey(key interface{}) ([]byte, error)
- func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
- func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)
- func MarshalSm2EcryptedPrivateKey(PrivKey *sm2.PrivateKey, pwd []byte) ([]byte, error)
- func MarshalSm2PrivateKey(key *sm2.PrivateKey, pwd []byte) ([]byte, error)
- func MarshalSm2PublicKey(key *sm2.PublicKey) ([]byte, error)
- func MarshalSm2UnecryptedPrivateKey(key *sm2.PrivateKey) ([]byte, error)
- func PKCS7Encrypt(content []byte, recipients []*Certificate) ([]byte, error)
- func PKCS7EncryptSM2(content []byte, recipients []*Certificate, mode int) ([]byte, error)
- func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)
- func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)
- func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
- func ParsePKCS8EcryptedPrivateKey(der, pwd []byte) (*sm2.PrivateKey, error)
- func ParsePKCS8PrivateKey(der, pwd []byte) (*sm2.PrivateKey, error)
- func ParsePKCS8PrivateKey2(der []byte) (key interface{}, err error)
- func ParsePKCS8UnecryptedPrivateKey(der []byte) (*sm2.PrivateKey, error)
- func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)
- func ParseSm2CertifateToX509(asn1data []byte) (*x509.Certificate, error)
- func ParseSm2PrivateKey(der []byte) (*sm2.PrivateKey, error)
- func ParseSm2PublicKey(der []byte) (*sm2.PublicKey, error)
- func ReadPrivateKeyFromHex(Dhex string) (*sm2.PrivateKey, error)
- func ReadPrivateKeyFromMem(data []byte, pwd []byte) (*sm2.PrivateKey, error)
- func ReadPrivateKeyFromPem(privateKeyPem []byte, pwd []byte) (*sm2.PrivateKey, error)
- func ReadPrivateKeyFromPemFile(FileName string, pwd []byte) (*sm2.PrivateKey, error)
- func ReadPublicKeyFromHex(Qhex string) (*sm2.PublicKey, error)
- func ReadPublicKeyFromMem(data []byte, _ []byte) (*sm2.PublicKey, error)
- func ReadPublicKeyFromPem(publicKeyPem []byte) (*sm2.PublicKey, error)
- func ReadPublicKeyFromPemFile(FileName string, pwd []byte) (*sm2.PublicKey, error)
- func RegisterHash(h Hash, f func() hash.Hash)
- func TestPKCS7SM2(t *testing.T)
- func WritePrivateKeyToHex(key *sm2.PrivateKey) string
- func WritePrivateKeyToPem(key *sm2.PrivateKey, pwd []byte) ([]byte, error)
- func WritePrivateKeytoMem(key *sm2.PrivateKey, pwd []byte) ([]byte, error)
- func WritePrivateKeytoPem(FileName string, key *sm2.PrivateKey, pwd []byte) (bool, error)
- func WritePublicKeyToHex(key *sm2.PublicKey) string
- func WritePublicKeyToPem(key *sm2.PublicKey) ([]byte, error)
- func WritePublicKeytoMem(key *sm2.PublicKey, _ []byte) ([]byte, error)
- func WritePublicKeytoPem(FileName string, key *sm2.PublicKey, _ []byte) (bool, error)
- type Attribute
- type CertPool
- type Certificate
- func ParseCertificate(asn1Data []byte) (*Certificate, error)
- func ParseCertificates(asn1Data []byte) ([]*Certificate, error)
- func ReadCertificateFromMem(data []byte) (*Certificate, error)
- func ReadCertificateFromPem(certPem []byte) (*Certificate, error)
- func ReadCertificateFromPemFile(FileName string) (*Certificate, error)
- func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
- func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
- func (c *Certificate) CheckSignatureFrom(parent *Certificate) error
- func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, ...) (crlBytes []byte, err error)
- func (c *Certificate) Equal(other *Certificate) bool
- func (c *Certificate) FromX509Certificate(x509Cert *x509.Certificate)
- func (c *Certificate) ToX509Certificate() *x509.Certificate
- func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
- func (c *Certificate) VerifyHostname(h string) error
- type CertificateInvalidError
- type CertificateRequest
- func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
- func ReadCertificateRequestFromMem(data []byte) (*CertificateRequest, error)
- func ReadCertificateRequestFromPem(certPem []byte) (*CertificateRequest, error)
- func ReadCertificateRequestFromPemFile(FileName string) (*CertificateRequest, error)
- type ConstraintViolationError
- type EncryptedPrivateKeyInfo
- type ExtKeyUsage
- type Hash
- type HostnameError
- type InsecureAlgorithmError
- type InvalidReason
- type KeyUsage
- type MessageDigestMismatchError
- type PEMCipher
- type PKCS7
- func (p7 *PKCS7) Decrypt(cert *Certificate, pk crypto.PrivateKey) ([]byte, error)
- func (p7 *PKCS7) DecryptSM2(cert *Certificate, pk crypto.PrivateKey, mode int) ([]byte, error)
- func (p7 *PKCS7) GetOnlySigner() *Certificate
- func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error
- func (p7 *PKCS7) Verify() (err error)
- type Pbes2Algorithms
- type Pbes2Encs
- type Pbes2KDfs
- type Pbes2Params
- type Pkdf2Params
- type PrivateKeyInfo
- type PublicKeyAlgorithm
- type RevocationList
- type SignatureAlgorithm
- type SignedData
- type SignerInfoConfig
- type SystemRootsError
- type UnhandledCriticalExtension
- type UnknownAuthorityError
- type VerifyOptions
Constants ¶
const ( EncryptionAlgorithmDESCBC = iota EncryptionAlgorithmAES128GCM )
Variables ¶
var ContentEncryptionAlgorithm = EncryptionAlgorithmDESCBC
ContentEncryptionAlgorithm determines the algorithm used to encrypt the plaintext message. Change the value of this variable to change which algorithm is used in the Encrypt() function.
var ErrIncorrectPassword = errors.New("x509: decryption password incorrect")
ErrIncorrectPassword is returned when an incorrect password is detected.
var ErrNotEncryptedContent = errors.New("pkcs7: content data is a decryptable data type")
ErrNotEncryptedContent is returned when attempting to Decrypt data that is not encrypted data
var ErrPKCS7UnsupportedAlgorithm = errors.New("pkcs7: cannot decrypt data: only RSA, DES, DES-EDE3, AES-256-CBC and AES-128-GCM supported")
ErrPKCS7UnsupportedAlgorithm tells you when our quick dev assumptions have failed
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.
var ErrUnsupportedContentType = errors.New("pkcs7: cannot parse data: unimplemented content type")
ErrUnsupportedContentType is returned when a PKCS7 content is not supported. Currently only Data (1.2.156.10197.6.1.4.2.1), Signed Data (1.2.156.10197.6.1.4.2.2), and Enveloped Data are supported (1.2.156.10197.6.1.4.2.3)
var ErrUnsupportedEncryptionAlgorithm = errors.New("pkcs7: cannot encrypt content: only DES-CBC and AES-128-GCM supported")
ErrUnsupportedEncryptionAlgorithm is returned when attempting to encrypt content with an unsupported algorithm.
Functions ¶
func CreateCertificate ¶
func CreateCertificate(template, parent *Certificate, publicKey interface{}, signer crypto.Signer) ([]byte, error)
根据证书模板与父证书生成新证书 template : 证书模板 *gmx509.Certificate parent : 父证书 *gmx509.Certificate publicKey : 新证书拥有者的公钥 (sm2/ecdsa/rsa) signer : 签名者(私钥)
func CreateCertificateFromReader ¶ added in v0.0.3
func CreateCertificateFromReader(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)
CreateCertificateToMem creates a new certificate based on a template. The following members of template are used: SerialNumber, Subject, NotBefore, NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, PermittedDNSDomains, SignatureAlgorithm.
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 signer and priv is the private key of the signer.
The returned slice is the certificate in PEM encoding.
All keys types that are implemented via crypto.Signer are supported (This includes *rsa.PublicKey and *ecdsa.PublicKey.) TODO CreateCertificate -> CreateCertificateFromReader 根据证书模板生成证书 template : 证书模板 parent : 父证书 pub : 证书拥有者的公钥 priv : 签名者的私钥(有父证书的话,就是父证书拥有者的私钥)
func CreateCertificateRequest ¶
func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, signer crypto.Signer) (csr []byte, err error)
CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used: Subject, Attributes, SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses. The private key is the private key of the signer.
The returned slice is the certificate request in DER encoding.
All keys types that are implemented via crypto.Signer are supported (This includes *rsa.PublicKey and *ecdsa.PublicKey.) 根据证书请求模板生成证书请求字节流 rand : 用于生成随机数的工具类库(io.Reader) template : 证书申请模板(*CertificateRequest) signer : 签名私钥(crypto.Signer) 注意,证书申请内部的公钥信息就是签名者的公钥,即,证书申请是申请者自签名的。
func CreateCertificateRequestToMem ¶ added in v0.0.3
func CreateCertificateRequestToMem(template *CertificateRequest, privKey *sm2.PrivateKey) ([]byte, error)
根据证书请求生成证书并转为pem字节流 template : 证书申请(*CertificateRequest) privKey : 签名私钥(*sm2.PrivateKey) 注意,证书申请内部公钥信息就是签名私钥的公钥,即,证书申请是申请者自签名的。
func CreateCertificateRequestToPem ¶
func CreateCertificateRequestToPem(template *CertificateRequest, signer crypto.Signer) ([]byte, error)
func CreateCertificateRequestToPemFile ¶ added in v0.0.3
func CreateCertificateRequestToPemFile(FileName string, template *CertificateRequest, privKey *sm2.PrivateKey) (bool, error)
TODO CreateCertificateRequestToPem -> CreateCertificateRequestToPemFile
func CreateCertificateToMem ¶ added in v0.0.3
func CreateCertificateToMem(template, parent *Certificate, pubKey, privKey interface{}) ([]byte, error)
根据证书模板生成证书,并转为pem字节流 template : 证书模板 parent : 父证书 pubKey : 证书拥有者公钥 privKey : 签名者私钥
func CreateCertificateToPem ¶
func CreateCertificateToPem(template, parent *Certificate, pubKey *sm2.PublicKey, signer crypto.Signer) ([]byte, error)
CreateCertificateToPem creates a new certificate based on a template and encodes it to PEM format. It uses CreateCertificate to create certificate and returns its PEM format.
func CreateCertificateToPemFile ¶ added in v0.0.3
func CreateCertificateToPemFile(FileName string, template, parent *Certificate, pubKey, privKey interface{}) (bool, error)
TODO CreateCertificateToPem -> CreateCertificateToPemFile
func CreateEllipticSKI ¶ added in v0.0.7
根据椭圆曲线公钥参数生成其SKI值
func CreateRevocationList ¶ added in v0.0.4
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 ¶ added in v0.0.7
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 IncorrectPasswordError 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 DegenerateCertificate ¶
DegenerateCertificate creates a signed data structure containing only the provided certificate or certificate chain.
func EncryptPEMBlock ¶ added in v0.0.7
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 IsEncryptedPEMBlock ¶ added in v0.0.7
IsEncryptedPEMBlock returns whether the PEM block is password encrypted according to RFC 1423.
func MarshalECPrivateKey ¶ added in v0.0.4
MarshalECPrivateKey marshals an EC private key into ASN.1, DER format. 将sm2私钥转为PKCS8格式字节流,不加密
func MarshalPKCS1PrivateKey ¶
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
func MarshalPKIXPublicKey ¶
MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
func MarshalSm2EcryptedPrivateKey ¶
func MarshalSm2EcryptedPrivateKey(PrivKey *sm2.PrivateKey, pwd []byte) ([]byte, error)
将sm2私钥转为pkcs8格式字节流,然后加密
func MarshalSm2PrivateKey ¶
func MarshalSm2PrivateKey(key *sm2.PrivateKey, pwd []byte) ([]byte, error)
将sm2私钥转为PKCS8格式字节流,根据pwd是否为空决定是否加密
func MarshalSm2PublicKey ¶
将sm2公钥转为PKIX标准的sm2公钥字节流
func MarshalSm2UnecryptedPrivateKey ¶
func MarshalSm2UnecryptedPrivateKey(key *sm2.PrivateKey) ([]byte, error)
将sm2私钥转为pkcs8格式字节流,不对私钥加密
func PKCS7Encrypt ¶
func PKCS7Encrypt(content []byte, recipients []*Certificate) ([]byte, error)
Encrypt creates and returns an envelope data PKCS7 structure with encrypted recipient keys for each recipient public key.
The algorithm used to perform encryption is determined by the current value of the global ContentEncryptionAlgorithm package variable. By default, the value is EncryptionAlgorithmDESCBC. To use a different algorithm, change the value before calling Encrypt(). For example:
ContentEncryptionAlgorithm = EncryptionAlgorithmAES128GCM
TODO(fullsailor): Add support for encrypting content with other algorithms
func PKCS7EncryptSM2 ¶ added in v0.0.4
func PKCS7EncryptSM2(content []byte, recipients []*Certificate, mode int) ([]byte, error)
func ParseCRL ¶
func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)
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 parses a DER encoded CRL from the given bytes.
func ParsePKCS1PrivateKey ¶
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
func ParsePKCS8EcryptedPrivateKey ¶
func ParsePKCS8EcryptedPrivateKey(der, pwd []byte) (*sm2.PrivateKey, error)
将加密的pkcs8格式私钥字节流转为sm2私钥
func ParsePKCS8PrivateKey ¶
func ParsePKCS8PrivateKey(der, pwd []byte) (*sm2.PrivateKey, error)
将PKCS8格式字节流转为sm2私钥,根据pwd是否为空决定是否需要解密
func ParsePKCS8PrivateKey2 ¶ added in v0.0.4
ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See RFC 5208.
func ParsePKCS8UnecryptedPrivateKey ¶
func ParsePKCS8UnecryptedPrivateKey(der []byte) (*sm2.PrivateKey, error)
将未加密的pkcs8格式私钥字节流转为sm2私钥
func ParsePKIXPublicKey ¶
ParsePKIXPublicKey parses a DER encoded public key. These values are typically found in PEM blocks with "BEGIN PUBLIC KEY".
Supported key types include RSA, DSA, and ECDSA. Unknown key types result in an error.
On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey, or *ecdsa.PublicKey.
func ParseSm2CertifateToX509 ¶
func ParseSm2CertifateToX509(asn1data []byte) (*x509.Certificate, error)
func ParseSm2PrivateKey ¶
func ParseSm2PrivateKey(der []byte) (*sm2.PrivateKey, error)
将sm2私钥字节流转为sm2私钥
func ParseSm2PublicKey ¶
将PKIX标准的sm2公钥字节流转为sm2公钥
func ReadPrivateKeyFromHex ¶
func ReadPrivateKeyFromHex(Dhex string) (*sm2.PrivateKey, error)
读取16进制的数字D作为私钥,Dhex是sm2私钥的16进制字符串,对应sm2.PrivateKey.D
func ReadPrivateKeyFromMem ¶ added in v0.0.3
func ReadPrivateKeyFromMem(data []byte, pwd []byte) (*sm2.PrivateKey, error)
将pem字节流转为sm2私钥
func ReadPrivateKeyFromPem ¶
func ReadPrivateKeyFromPem(privateKeyPem []byte, pwd []byte) (*sm2.PrivateKey, error)
func ReadPrivateKeyFromPemFile ¶ added in v0.0.3
func ReadPrivateKeyFromPemFile(FileName string, pwd []byte) (*sm2.PrivateKey, error)
TODO rename ReadPrivateKeyFromPem -> ReadPrivateKeyFromPemFile
func ReadPublicKeyFromMem ¶ added in v0.0.3
将pem字节流转为sm2公钥
func ReadPublicKeyFromPemFile ¶ added in v0.0.3
TODO ReadPublicKeyFromPem -> ReadPublicKeyFromPemFile
func RegisterHash ¶
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 TestPKCS7SM2 ¶ added in v0.0.7
func WritePrivateKeyToHex ¶
func WritePrivateKeyToHex(key *sm2.PrivateKey) string
func WritePrivateKeyToPem ¶
func WritePrivateKeyToPem(key *sm2.PrivateKey, pwd []byte) ([]byte, error)
func WritePrivateKeytoMem ¶ added in v0.0.3
func WritePrivateKeytoMem(key *sm2.PrivateKey, pwd []byte) ([]byte, error)
将sm2私钥转为PKCS8格式字节流,根据pwd决定是否加密,然后包装为pem字节流
func WritePrivateKeytoPem ¶ added in v0.0.3
func WritePublicKeyToHex ¶
func WritePublicKeytoMem ¶ added in v0.0.3
将sm2公钥转为PKIX格式字节流并包装为pem字节流
Types ¶
type Attribute ¶
type Attribute struct { Type asn1.ObjectIdentifier Value interface{} }
Attribute represents a key value pair attribute. Value must be marshalable byte `encoding/asn1`
type CertPool ¶
type CertPool struct {
// contains filtered or unexported fields
}
CertPool is a set of certificates.
func SystemCertPool ¶
SystemCertPool returns a copy of the system cert pool.
Any mutations to the returned pool are not written to disk and do not affect any other pool.
func (*CertPool) AddCert ¶
func (s *CertPool) AddCert(cert *Certificate)
AddCert adds a certificate to a pool.
func (*CertPool) AppendCertsFromPEM ¶
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.
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 // 签名 Signature []byte // 签名算法 SignatureAlgorithm SignatureAlgorithm // 证书拥有者的公钥算法 PublicKeyAlgorithm PublicKeyAlgorithm // 证书拥有者的公钥(证书的核心内容) PublicKey interface{} // 证书版本 Version int // 证书序列号 SerialNumber *big.Int // 证书签署者(提供私钥对RawTBSCertificate进行签名) Issuer pkix.Name // 证书拥有者(该证书的核心公钥的拥有者) Subject pkix.Name // 证书有效期间 NotBefore, NotAfter time.Time // Validity bounds. // 证书公钥的用途 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 是否有效 // if true then the next two fields are valid. BasicConstraintsValid bool // 是否CA证书 IsCA bool 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公钥为例,计算方式为 将椭圆曲线上的公钥座标转换为字节流再做sha256散列 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 DNSNames []string EmailAddresses []string IPAddresses []net.IP // Name constraints PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. PermittedDNSDomains []string ExcludedDNSDomains []string // CRL Distribution Points CRLDistributionPoints []string PolicyIdentifiers []asn1.ObjectIdentifier }
gmx509证书结构体 A Certificate represents an X.509 certificate.
func ParseCertificate ¶
func ParseCertificate(asn1Data []byte) (*Certificate, error)
ParseCertificate parses a single certificate from the given ASN.1 DER data.
func ParseCertificates ¶
func ParseCertificates(asn1Data []byte) ([]*Certificate, error)
ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.
func ReadCertificateFromMem ¶ added in v0.0.3
func ReadCertificateFromMem(data []byte) (*Certificate, error)
func ReadCertificateFromPem ¶
func ReadCertificateFromPem(certPem []byte) (*Certificate, error)
func ReadCertificateFromPemFile ¶ added in v0.0.3
func ReadCertificateFromPemFile(FileName string) (*Certificate, error)
TODO ReadCertificateFromPem -> ReadCertificateFromPemFile
func (*Certificate) CheckCRLSignature ¶
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
CheckCRLSignature checks that the signature in crl is from c.
func (*Certificate) CheckSignature ¶
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
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 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 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)
func (*Certificate) ToX509Certificate ¶
func (c *Certificate) ToX509Certificate() *x509.Certificate
func (*Certificate) Verify ¶
func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
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.
WARNING: this doesn't do any revocation checking.
func (*Certificate) VerifyHostname ¶
func (c *Certificate) VerifyHostname(h string) error
VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.
type CertificateInvalidError ¶
type CertificateInvalidError struct { Cert *Certificate Reason InvalidReason }
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 is the dried husk of a bug and shouldn't be used. Attributes []pkix.AttributeTypeAndValueSET // Extensions contains raw X.509 extensions. 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 // marshaled CSR. 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 when parsing CSRs, see // Extensions. ExtraExtensions []pkix.Extension // Subject Alternate Name values. DNSNames []string EmailAddresses []string IPAddresses []net.IP }
CertificateRequest represents a PKCS #10, certificate signature request.
func ParseCertificateRequest ¶
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.
func ReadCertificateRequestFromMem ¶ added in v0.0.3
func ReadCertificateRequestFromMem(data []byte) (*CertificateRequest, error)
func ReadCertificateRequestFromPem ¶
func ReadCertificateRequestFromPem(certPem []byte) (*CertificateRequest, error)
func ReadCertificateRequestFromPemFile ¶ added in v0.0.3
func ReadCertificateRequestFromPemFile(FileName string) (*CertificateRequest, error)
TODO ReadCertificateRequestFromPem -> ReadCertificateRequestFromPemFile
func (*CertificateRequest) CheckSignature ¶
func (c *CertificateRequest) CheckSignature() error
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 ¶
func (ConstraintViolationError) Error() string
type EncryptedPrivateKeyInfo ¶
type EncryptedPrivateKeyInfo struct { EncryptionAlgorithm Pbes2Algorithms EncryptedData []byte }
reference to https://www.rfc-editor.org/rfc/rfc5958.txt
type ExtKeyUsage ¶
type ExtKeyUsage int
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 )
type Hash ¶
type Hash uint
重写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 ¶
Available reports whether the given hash function is linked into the binary.
func (Hash) New ¶
New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.
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 include the name // being checked. 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 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 MessageDigestMismatchError ¶
MessageDigestMismatchError is returned when the signer data digest does not match the computed digest for the contained content
func (*MessageDigestMismatchError) Error ¶
func (err *MessageDigestMismatchError) Error() string
type PEMCipher ¶ added in v0.0.7
type PEMCipher int
const ( PEMCipherDES PEMCipher PEMCipher3DES PEMCipherAES128 PEMCipherAES192 PEMCipherAES256 )
Possible values for the EncryptPEMBlock encryption algorithm.
type PKCS7 ¶
type PKCS7 struct { Content []byte Certificates []*Certificate CRLs []pkix.CertificateList Signers []signerInfo // contains filtered or unexported fields }
PKCS7 Represents a PKCS7 structure
func ParsePKCS7 ¶
ParsePKCS7 decodes a DER encoded PKCS7.
func (*PKCS7) Decrypt ¶
func (p7 *PKCS7) Decrypt(cert *Certificate, pk crypto.PrivateKey) ([]byte, error)
Decrypt decrypts encrypted content info for recipient cert and private key
func (*PKCS7) DecryptSM2 ¶ added in v0.0.4
func (p7 *PKCS7) DecryptSM2(cert *Certificate, pk crypto.PrivateKey, mode int) ([]byte, error)
func (*PKCS7) GetOnlySigner ¶
func (p7 *PKCS7) GetOnlySigner() *Certificate
GetOnlySigner returns an x509.Certificate for the first signer of the signed data payload. If there are more or less than one signer, nil is returned
func (*PKCS7) UnmarshalSignedAttribute ¶
func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error
UnmarshalSignedAttribute decodes a single attribute from the signer info
type Pbes2Algorithms ¶
type Pbes2Algorithms struct { IdPBES2 asn1.ObjectIdentifier Pbes2Params Pbes2Params }
reference to https://www.ietf.org/rfc/rfc2898.txt
type Pbes2Encs ¶
type Pbes2Encs struct { EncryAlgo asn1.ObjectIdentifier IV []byte }
type Pbes2KDfs ¶
type Pbes2KDfs struct { IdPBKDF2 asn1.ObjectIdentifier Pkdf2Params Pkdf2Params }
reference to https://www.ietf.org/rfc/rfc2898.txt
type Pbes2Params ¶
type Pbes2Params struct { KeyDerivationFunc Pbes2KDfs // PBES2-KDFs EncryptionScheme Pbes2Encs // PBES2-Encs }
reference to https://www.ietf.org/rfc/rfc2898.txt
type Pkdf2Params ¶
type Pkdf2Params struct { Salt []byte IterationCount int Prf pkix.AlgorithmIdentifier }
reference to https://www.ietf.org/rfc/rfc2898.txt
type PrivateKeyInfo ¶
type PrivateKeyInfo struct { Version int // v1 or v2 PrivateKeyAlgorithm []asn1.ObjectIdentifier PrivateKey []byte }
reference to https://www.rfc-editor.org/rfc/rfc5958.txt
type PublicKeyAlgorithm ¶
type PublicKeyAlgorithm int
const ( UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota RSA DSA ECDSA SM2 )
func GetPubKeyTypeFromCert ¶ added in v0.0.4
func GetPubKeyTypeFromCert(asn1Data []byte) (PublicKeyAlgorithm, error)
从asn1的字节数组中获取公钥算法
func (PublicKeyAlgorithm) String ¶ added in v0.0.4
func (algo PublicKeyAlgorithm) String() string
type RevocationList ¶ added in v0.0.4
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
const ( UnknownSignatureAlgorithm SignatureAlgorithm = iota MD2WithRSA MD5WithRSA // SM3WithRSA reserve SHA1WithRSA SHA256WithRSA SHA384WithRSA SHA512WithRSA DSAWithSHA1 DSAWithSHA256 ECDSAWithSHA1 ECDSAWithSHA256 ECDSAWithSHA384 ECDSAWithSHA512 SHA256WithRSAPSS SHA384WithRSAPSS SHA512WithRSAPSS SM2WithSM3 SM2WithSHA1 SM2WithSHA256 )
func (SignatureAlgorithm) String ¶
func (algo SignatureAlgorithm) String() string
type SignedData ¶
type SignedData struct {
// contains filtered or unexported fields
}
SignedData is an opaque data structure for creating signed data payloads
func NewSignedData ¶
func NewSignedData(data []byte) (*SignedData, error)
NewSignedData initializes a SignedData with content
func (*SignedData) AddCertificate ¶
func (sd *SignedData) AddCertificate(cert *Certificate)
AddCertificate adds the certificate to the payload. Useful for parent certificates
func (*SignedData) AddSigner ¶
func (sd *SignedData) AddSigner(cert *Certificate, pkey crypto.PrivateKey, config SignerInfoConfig) error
AddSigner signs attributes about the content and adds certificate to payload
func (*SignedData) Detach ¶
func (sd *SignedData) Detach()
Detach removes content from the signed data struct to make it a detached signature. This must be called right before Finish()
func (*SignedData) Finish ¶
func (sd *SignedData) Finish() ([]byte, error)
Finish marshals the content and its signers
type SignerInfoConfig ¶
type SignerInfoConfig struct {
ExtraSignedAttributes []Attribute
}
SignerInfoConfig are optional values to include when adding a signer
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
type UnhandledCriticalExtension ¶
type UnhandledCriticalExtension struct{}
func (UnhandledCriticalExtension) Error ¶
func (h UnhandledCriticalExtension) Error() string
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 string Intermediates *CertPool Roots *CertPool // if nil, the system roots are used CurrentTime time.Time // if zero, the current time is used // KeyUsage specifies which Extended Key Usage values are acceptable. // An empty list means ExtKeyUsageServerAuth. Key usage is considered a // constraint down the chain which mirrors Windows CryptoAPI behavior, // but not the spec. To accept any key usage, include ExtKeyUsageAny. KeyUsages []ExtKeyUsage }
VerifyOptions contains parameters for Certificate.Verify. It's a structure because other PKIX verification APIs have ended up needing many options.