smx509

package
v0.26.1 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2024 License: MIT Imports: 44 Imported by: 51

Documentation

Overview

Package smx509 parses X.509-encoded keys and certificates include SM2/SM3 support.

It allows parsing and generating certificates, certificate signing requests, certificate revocation lists, and encoded public and private keys. It provides a certificate verifier, complete with a chain builder.

The package targets the X.509 technical profile defined by the IETF (RFC 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline Requirements. There is minimal support for features outside of these profiles, as the primary goal of the package is to provide compatibility with the publicly trusted TLS certificate ecosystem and its policies and constraints.

On Windows, certificate verification is handled by system APIs, but the package aims to apply consistent validation rules across operating systems.

On macOS, we did NOT support to use system root CA yet due to too many SDK internal package's dependencies.

Index

Examples

Constants

View Source
const (
	NotAuthorizedToSign           = x509.NotAuthorizedToSign
	Expired                       = x509.Expired
	CANotAuthorizedForThisName    = x509.CANotAuthorizedForThisName
	TooManyIntermediates          = x509.TooManyIntermediates
	IncompatibleUsage             = x509.IncompatibleUsage
	NameMismatch                  = x509.NameMismatch
	NameConstraintsWithoutSANs    = x509.NameConstraintsWithoutSANs
	UnconstrainedName             = x509.UnconstrainedName
	TooManyConstraints            = x509.TooManyConstraints
	CANotAuthorizedForExtKeyUsage = x509.CANotAuthorizedForExtKeyUsage
)
View Source
const (
	UnknownSignatureAlgorithm = x509.UnknownSignatureAlgorithm

	MD2WithRSA       = x509.MD2WithRSA
	MD5WithRSA       = x509.MD5WithRSA // Only supported for signing, not verification.
	SHA1WithRSA      = x509.SHA1WithRSA
	SHA256WithRSA    = x509.SHA256WithRSA
	SHA384WithRSA    = x509.SHA384WithRSA
	SHA512WithRSA    = x509.SHA512WithRSA
	DSAWithSHA1      = x509.DSAWithSHA1   // Unsupported.
	DSAWithSHA256    = x509.DSAWithSHA256 // Unsupported.
	ECDSAWithSHA1    = x509.ECDSAWithSHA1
	ECDSAWithSHA256  = x509.ECDSAWithSHA256
	ECDSAWithSHA384  = x509.ECDSAWithSHA384
	ECDSAWithSHA512  = x509.ECDSAWithSHA512
	SHA256WithRSAPSS = x509.SHA256WithRSAPSS
	SHA384WithRSAPSS = x509.SHA384WithRSAPSS
	SHA512WithRSAPSS = x509.SHA512WithRSAPSS
	PureEd25519      = x509.PureEd25519

	SM2WithSM3 SignatureAlgorithm = 99
)
View Source
const (
	UnknownPublicKeyAlgorithm = x509.UnknownPublicKeyAlgorithm

	RSA     = x509.RSA
	DSA     = x509.DSA // Only supported for parsing.
	ECDSA   = x509.ECDSA
	Ed25519 = x509.Ed25519
)
View Source
const (
	KeyUsageDigitalSignature  = x509.KeyUsageDigitalSignature
	KeyUsageContentCommitment = x509.KeyUsageContentCommitment
	KeyUsageKeyEncipherment   = x509.KeyUsageKeyEncipherment
	KeyUsageDataEncipherment  = x509.KeyUsageDataEncipherment
	KeyUsageKeyAgreement      = x509.KeyUsageKeyAgreement
	KeyUsageCertSign          = x509.KeyUsageCertSign
	KeyUsageCRLSign           = x509.KeyUsageCRLSign
	KeyUsageEncipherOnly      = x509.KeyUsageEncipherOnly
	KeyUsageDecipherOnly      = x509.KeyUsageDecipherOnly
)
View Source
const (
	ExtKeyUsageAny                            = x509.ExtKeyUsageAny
	ExtKeyUsageServerAuth                     = x509.ExtKeyUsageServerAuth
	ExtKeyUsageClientAuth                     = x509.ExtKeyUsageClientAuth
	ExtKeyUsageCodeSigning                    = x509.ExtKeyUsageCodeSigning
	ExtKeyUsageEmailProtection                = x509.ExtKeyUsageEmailProtection
	ExtKeyUsageIPSECEndSystem                 = x509.ExtKeyUsageIPSECEndSystem
	ExtKeyUsageIPSECTunnel                    = x509.ExtKeyUsageIPSECTunnel
	ExtKeyUsageIPSECUser                      = x509.ExtKeyUsageIPSECUser
	ExtKeyUsageTimeStamping                   = x509.ExtKeyUsageTimeStamping
	ExtKeyUsageOCSPSigning                    = x509.ExtKeyUsageOCSPSigning
	ExtKeyUsageMicrosoftServerGatedCrypto     = x509.ExtKeyUsageMicrosoftServerGatedCrypto
	ExtKeyUsageNetscapeServerGatedCrypto      = x509.ExtKeyUsageNetscapeServerGatedCrypto
	ExtKeyUsageMicrosoftCommercialCodeSigning = x509.ExtKeyUsageMicrosoftCommercialCodeSigning
	ExtKeyUsageMicrosoftKernelCodeSigning     = x509.ExtKeyUsageMicrosoftKernelCodeSigning
)

Variables

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

IncorrectPasswordError is returned when an incorrect password is detected.

Functions

func CreateCertificate added in v0.3.0

func CreateCertificate(rand io.Reader, template, parent, pub, priv any) ([]byte, error)

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, both parent and template should be *x509.Certificate or *smx509.Certificate type. 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 *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 *x509.CertificateRequest, priv any) (csr []byte, err error)

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 CreateRevocationList added in v0.7.0

func CreateRevocationList(rand io.Reader, template *x509.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 deprecated added in v0.11.5

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 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.

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

func EncryptPEMBlock deprecated added in v0.11.5

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.

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

func IsEncryptedPEMBlock deprecated added in v0.11.5

func IsEncryptedPEMBlock(b *pem.Block) bool

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

Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

func MarshalECPrivateKey added in v0.3.0

func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)

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 added in v0.15.2

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

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 added in v0.15.2

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

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 added in v0.3.0

func MarshalPKCS8PrivateKey(key any) ([]byte, error)

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

The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey, a *sm2.PrivateKey, a *ecdh.PrivateKey a *sm9.SignMasterPrivateKey, a *sm9.SignPrivateKey, a *sm9.EncryptMasterPrivateKey, a *sm9.EncryptPrivateKey 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 any) ([]byte, error)

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 MarshalSM2PrivateKey added in v0.3.0

func MarshalSM2PrivateKey(key *sm2.PrivateKey) ([]byte, error)

MarshalSM2PrivateKey convient method to marshal sm2 private key directly

func ParseCRL added in v0.4.8

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 added in v0.4.8

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

ParseDERCRL parses a DER encoded CRL from the given bytes.

func ParseECPrivateKey added in v0.3.0

func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)

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 ParseName added in v0.15.3

func ParseName(raw cryptobyte.String) (*pkix.RDNSequence, error)

ParseName parses a DER encoded Name as defined in RFC 5280.

func ParsePKCS1PrivateKey added in v0.15.2

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

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 added in v0.15.2

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

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 added in v0.3.0

func ParsePKCS8PrivateKey(der []byte) (key any, err error)

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

It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, a *sm2.PrivateKey, a *sm9.SignMasterPrivateKey, a *sm9.SignPrivateKey, a *sm9.EncryptMasterPrivateKey, a *sm9.EncryptPrivateKey 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".

Example
package main

import (
	"encoding/pem"
	"fmt"

	"github.com/emmansun/gmsm/sm2"
	"github.com/emmansun/gmsm/smx509"
)

func main() {
	const privPEM = `
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBG0wawIBAQQgW+2/sIbWJ5bqzQ4D
Vh8sQ2B/6I1PLGIcItXgGxAcdA6hRANCAAQ/Sx9dzxrMJwgoHmQ76X6g4EoM/2ca
Cm0E4OyvrAVYYipqoI2JhFccq9ZYC5cA9cMj9JW0l5fBtSHp3dSd6wNH
-----END PRIVATE KEY-----`
	block, _ := pem.Decode([]byte(privPEM))
	if block == nil {
		panic("failed to parse PEM block containing the private key")
	}
	key, err := smx509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		panic("failed to parse DER encoded private key: " + err.Error())
	}
	switch priv := key.(type) {
	case *sm2.PrivateKey:
		fmt.Println("priv is of type SM2:", priv.Params().Name)
	default:
		panic("unexpected type of private key")
	}
}
Output:

priv is of type SM2: sm2p256v1

func ParsePKIXPublicKey

func ParsePKIXPublicKey(derBytes []byte) (any, error)

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/dsa"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/rsa"

	"encoding/pem"
	"fmt"

	"github.com/emmansun/gmsm/sm2"
	"github.com/emmansun/gmsm/smx509"
)

func main() {
	const pubPEM = `
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAENpoOih+9ASfmKYx5lK5mLsrUK3Am
B6kLUsqHlVyglXgoMEwo8Sr8xb/Q3gDMNnd7Wyp2bJE9ksb60ansO4QaKg==
-----END PUBLIC KEY-----`

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

	pub, err := smx509.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.Curve.Params().Name)
	case ed25519.PublicKey:
		fmt.Println("pub is of type Ed25519:", pub)
	default:
		panic("unknown type of public key")
	}
	isSM2 := sm2.IsSM2PublicKey(pub)
	fmt.Printf("%v\n", isSM2)
}
Output:

pub is of type ECDSA: sm2p256v1
true

func ParseSM2PrivateKey added in v0.3.0

func ParseSM2PrivateKey(der []byte) (*sm2.PrivateKey, error)

ParseSM2PrivateKey parses an SM2 private key in SEC 1, ASN.1 DER form.

Example
package main

import (
	"encoding/pem"
	"fmt"
	"strings"

	"github.com/emmansun/gmsm/smx509"
)

func main() {
	// Of course, you can remove EC PARAMETERS to make it simple.
	// https://security.stackexchange.com/questions/29778/why-does-openssl-writes-ec-parameters-when-generating-private-key
	const privPEM = `	
-----BEGIN EC PARAMETERS-----
BggqgRzPVQGCLQ==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIFvtv7CG1ieW6s0OA1YfLENgf+iNTyxiHCLV4BsQHHQOoAoGCCqBHM9V
AYItoUQDQgAEP0sfXc8azCcIKB5kO+l+oOBKDP9nGgptBODsr6wFWGIqaqCNiYRX
HKvWWAuXAPXDI/SVtJeXwbUh6d3UnesDRw==
-----END EC PRIVATE KEY-----`
	var keyDERBlock *pem.Block
	keyPEMBlock := []byte(privPEM)
	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			break
		}
		if keyDERBlock.Type == "EC PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}
	}
	if keyDERBlock == nil {
		panic("failed to parse PEM block containing the private key")
	}

	key, err := smx509.ParseSM2PrivateKey(keyDERBlock.Bytes)
	if err != nil {
		panic("failed to parse DER encoded private key: " + err.Error())
	}
	fmt.Println("priv is of type SM2:", key.Params().Name)
}
Output:

priv is of type SM2: sm2p256v1

func ParseTypedECPrivateKey added in v0.15.7

func ParseTypedECPrivateKey(der []byte) (any, error)

ParseTypedECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.

It returns a *ecdsa.PrivateKey or a *sm2.PrivateKey.

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

Example
package main

import (
	"encoding/asn1"
	"encoding/pem"
	"fmt"
	"strings"

	"github.com/emmansun/gmsm/sm2"
	"github.com/emmansun/gmsm/smx509"
)

func main() {
	// Of course, you can remove EC PARAMETERS to make it simple.
	// https://security.stackexchange.com/questions/29778/why-does-openssl-writes-ec-parameters-when-generating-private-key
	const privPEM = `	
-----BEGIN EC PARAMETERS-----
BggqgRzPVQGCLQ==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIFvtv7CG1ieW6s0OA1YfLENgf+iNTyxiHCLV4BsQHHQOoAoGCCqBHM9V
AYItoUQDQgAEP0sfXc8azCcIKB5kO+l+oOBKDP9nGgptBODsr6wFWGIqaqCNiYRX
HKvWWAuXAPXDI/SVtJeXwbUh6d3UnesDRw==
-----END EC PRIVATE KEY-----`
	var keyDERBlock *pem.Block
	keyPEMBlock := []byte(privPEM)
	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			break
		}
		if keyDERBlock.Type == "EC PARAMETERS" {
			var oid asn1.ObjectIdentifier
			_, err := asn1.Unmarshal(keyDERBlock.Bytes, &oid)
			if err != nil {
				panic("failed to parse private key ecparams")
			}
			fmt.Printf("%v\n", oid)
		}
		if keyDERBlock.Type == "EC PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}
	}
	if keyDERBlock == nil {
		panic("failed to parse PEM block containing the private key")
	}

	key, err := smx509.ParseTypedECPrivateKey(keyDERBlock.Bytes)
	if err != nil {
		panic("failed to parse DER encoded private key: " + err.Error())
	}
	switch priv := key.(type) {
	case *sm2.PrivateKey:
		fmt.Println("priv is of type SM2:", priv.Params().Name)
	default:
		panic("unexpected type of private key")
	}
}
Output:

1.2.156.10197.1.301
priv is of type SM2: sm2p256v1

func SetFallbackRoots added in v0.26.1

func SetFallbackRoots(roots *CertPool)

SetFallbackRoots sets the roots to use during certificate verification, if no custom roots are specified and a platform verifier or a system certificate pool is not available (for instance in a container which does not have a root certificate bundle). SetFallbackRoots will panic if roots is nil.

SetFallbackRoots may only be called once, if called multiple times it will panic.

The fallback behavior can be forced on all platforms, even when there is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that on Windows and macOS this will disable usage of the platform verification APIs and cause the pure Go verifier to be used). Setting x509usefallbackroots=1 without calling SetFallbackRoots has no effect.

Types

type CertPool added in v0.3.0

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

CertPool is a set of certificates.

func NewCertPool added in v0.3.0

func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

func SystemCertPool added in v0.3.0

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 added in v0.3.0

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

AddCert adds a certificate to a pool.

func (*CertPool) AddCertWithConstraint added in v0.26.1

func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)

AddCertWithConstraint adds a certificate to the pool with the additional constraint. When Certificate.Verify builds a chain which is rooted by cert, it will additionally pass the whole chain to constraint to determine its validity. If constraint returns a non-nil error, the chain will be discarded. constraint may be called concurrently from multiple goroutines.

func (*CertPool) AppendCertsFromPEM added in v0.3.0

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) Clone added in v0.11.5

func (s *CertPool) Clone() *CertPool

Clone returns a copy of s.

func (*CertPool) Equal added in v0.11.5

func (s *CertPool) Equal(other *CertPool) bool

Equal reports whether s and other are equal.

func (*CertPool) Subjects deprecated added in v0.3.0

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

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

Deprecated: if s was returned by SystemCertPool, Subjects will not include the system roots.

type Certificate added in v0.3.0

type Certificate x509.Certificate

A Certificate represents an X.509 certificate.

func ParseCertificate added in v0.3.0

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

ParseCertificate parses a single certificate from the given ASN.1 DER data.

func ParseCertificatePEM added in v0.4.8

func ParseCertificatePEM(data []byte) (*Certificate, error)

func ParseCertificates added in v0.3.0

func ParseCertificates(der []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 (*Certificate) CheckCRLSignature added in v0.3.1

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

CheckCRLSignature checks that the signature in crl is from c.

func (*Certificate) CheckSignature added in v0.3.0

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.

This is a low-level API that performs no validity checks on the certificate.

MD5WithRSA signatures are rejected, while SHA1WithRSA and ECDSAWithSHA1 signatures are currently accepted.

func (*Certificate) CheckSignatureFrom added in v0.3.0

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

CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

This is a low-level API that performs very limited checks, and not a full path verifier. Most users should use Certificate.Verify instead.

func (*Certificate) CreateCRL added in v0.3.0

func (c *Certificate) CreateCRL(rand io.Reader, priv any, 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 added in v0.3.0

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

func (*Certificate) ToX509 added in v0.11.5

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

ToX509 convert smx509.Certificate reference to x509.Certificate

func (*Certificate) Verify added in v0.3.0

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, 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.

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.

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.)

Certificates other than c in the returned chains should not be modified.

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

func (*Certificate) VerifyHostname added in v0.3.0

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.

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 complete left-most label (e.g. *.example.com).

Note that the legacy Common Name field is ignored.

type CertificateInvalidError added in v0.3.0

type CertificateInvalidError = x509.CertificateInvalidError

type CertificateRequest added in v0.3.0

type CertificateRequest x509.CertificateRequest

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 ParseCertificateRequestPEM added in v0.4.8

func ParseCertificateRequestPEM(data []byte) (*CertificateRequest, error)

ParseCertificateRequestPEM parses a single certificate request from the given PEM data.

func (*CertificateRequest) CheckSignature added in v0.3.0

func (c *CertificateRequest) CheckSignature() error

CheckSignature reports whether the signature on c is valid.

func (*CertificateRequest) ToX509 added in v0.11.5

ToX509 convert smx509.CertificateRequest reference to x509.CertificateRequest

type ExtKeyUsage added in v0.11.0

type ExtKeyUsage = x509.ExtKeyUsage

ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.

type KeyUsage added in v0.11.0

type KeyUsage = x509.KeyUsage

KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.

type PEMCipher added in v0.11.5

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

Possible values for the EncryptPEMBlock encryption algorithm.

type PublicKeyAlgorithm added in v0.11.0

type PublicKeyAlgorithm = x509.PublicKeyAlgorithm

type SignatureAlgorithm added in v0.11.0

type SignatureAlgorithm = x509.SignatureAlgorithm

type UnknownAuthorityError added in v0.3.0

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

UnknownAuthorityError results when the certificate issuer is unknown

func (UnknownAuthorityError) Error added in v0.3.0

func (e UnknownAuthorityError) Error() string

type VerifyOptions added in v0.3.0

type VerifyOptions struct {
	// 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 is used to check the validity of all certificates in the
	// chain. If zero, the current time is used.
	CurrentTime time.Time

	// 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 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