x509
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package x509 implements a subset of the X.509 standard.
It allows parsing and generating certificates, certificate signingrequests, 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 (RFC2459/3280/5280), and as further restricted by the CA/Browser Forum BaselineRequirements. There is minimal support for features outside of theseprofiles, as the primary goal of the package is to provide compatibilitywith the publicly trusted TLS certificate ecosystem and its policies andconstraints.
On macOS and Windows, certificate verification is handled by system APIs, butthe package aims to apply consistent validation rules across operatingsystems.
Index¶
- Variables
- func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)
- func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)
- func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, ...) ([]byte, error)
- func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)deprecated
- func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)deprecated
- func IsEncryptedPEMBlock(b *pem.Block) booldeprecated
- func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
- func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
- func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte
- func MarshalPKCS8PrivateKey(key any) ([]byte, error)
- func MarshalPKIXPublicKey(pub any) ([]byte, error)
- func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)deprecated
- func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)deprecated
- func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
- func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
- func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)
- func ParsePKCS8PrivateKey(der []byte) (key any, err error)
- func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)
- func SetFallbackRoots(roots *CertPool)
- type CertPool
- func (s *CertPool) AddCert(cert *Certificate)
- func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)
- func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
- func (s *CertPool) Clone() *CertPool
- func (s *CertPool) Equal(other *CertPool) bool
- func (s *CertPool) Subjects() [][]bytedeprecated
- type Certificate
- func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) errordeprecated
- 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 any, revokedCerts []pkix.RevokedCertificate, ...) (crlBytes []byte, err error)deprecated
- func (c *Certificate) Equal(other *Certificate) bool
- func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
- func (c *Certificate) VerifyHostname(h string) error
- type CertificateInvalidError
- type CertificateRequest
- type ConstraintViolationError
- type ExtKeyUsage
- type HostnameError
- type InsecureAlgorithmError
- type InvalidReason
- type KeyUsage
- type OID
- func (o OID) AppendBinary(b []byte) ([]byte, error)
- func (o OID) AppendText(b []byte) ([]byte, error)
- func (oid OID) Equal(other OID) bool
- func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool
- func (o OID) MarshalBinary() ([]byte, error)
- func (o OID) MarshalText() ([]byte, error)
- func (oid OID) String() string
- func (o *OID) UnmarshalBinary(b []byte) error
- func (o *OID) UnmarshalText(text []byte) error
- type PEMCipher
- type PolicyMapping
- type PublicKeyAlgorithm
- type RevocationList
- type RevocationListEntry
- type SignatureAlgorithm
- type SystemRootsError
- type UnhandledCriticalExtension
- type UnknownAuthorityError
- type VerifyOptions
Examples¶
Constants¶
This section is empty.
Variables¶
var ErrUnsupportedAlgorithm =errors.New("x509: cannot verify signature: algorithm unimplemented")ErrUnsupportedAlgorithm results from attempting to perform an operation thatinvolves algorithms that are not currently implemented.
var IncorrectPasswordError =errors.New("x509: decryption password incorrect")IncorrectPasswordError is returned when an incorrect password is detected.
Functions¶
funcCreateCertificate¶
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 (see note below)
- Policies (see note below)
- SerialNumber
- SignatureAlgorithm
- Subject
- SubjectKeyId
- URIs
- UnknownExtKeyUsage
The certificate is signed by parent. If parent is equal to template then thecertificate is self-signed. The parameter pub is the public key of thecertificate 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 anded25519.PublicKey. pub must be a supported key type, and priv must be acrypto.Signer or crypto.MessageSigner 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 fromtemplate will be used.
If SubjectKeyId from template is empty and the template is a CA, SubjectKeyIdwill be generated from the hash of the public key.
If template.SerialNumber is nil, a serial number will be generated whichconforms toRFC 5280, Section 4.1.2.2 using entropy from rand.
The PolicyIdentifier and Policies fields can both be used to marshal certificatepolicy OIDs. By default, only the Policies is marshaled, but if theGODEBUG setting "x509usepolicies" has the value "0", the PolicyIdentifiers field willbe marshaled instead of the Policies field. This changed in Go 1.24. The Policies field canbe used to marshal policy OIDs which have components that are larger than 31bits.
funcCreateCertificateRequest¶added ingo1.3
func CreateCertificateRequest(randio.Reader, template *CertificateRequest, privany) (csr []byte, errerror)
CreateCertificateRequest creates a new certificate request based on atemplate. 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 publickey will be included in the CSR. It must implement crypto.Signer orcrypto.MessageSigner and its Public() method must return a *rsa.PublicKey ora *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.
funcCreateRevocationList¶added ingo1.15
func CreateRevocationList(randio.Reader, template *RevocationList, issuer *Certificate, privcrypto.Signer) ([]byte,error)
CreateRevocationList creates a new X.509 v2Certificate Revocation List,according toRFC 5280, based on template.
The CRL is signed by priv which should be a crypto.Signer orcrypto.MessageSigner associated with the public key in the issuercertificate.
The issuer may not be nil, and the crlSign bit must be set inKeyUsage inorder to use it as a CRL issuer.
The issuer distinguished name CRL field and authority key identifierextension are populated using the issuer certificate. issuer must haveSubjectKeyId set.
funcDecryptPEMBlockdeprecatedadded ingo1.1
DecryptPEMBlock takes a PEM block encrypted according toRFC 1423 and thepassword used to encrypt it and returns a slice of decrypted DER encodedbytes. It inspects the DEK-Info header to determine the algorithm used fordecryption. If no DEK-Info header is present, an error is returned. If anincorrect password is detected anIncorrectPasswordError is returned. Becauseof deficiencies in the format, it's not always possible to detect anincorrect password. In these cases no error will be returned but thedecrypted DER bytes will be random noise.
Deprecated: Legacy PEM encryption as specified inRFC 1423 is insecure bydesign. Since it does not authenticate the ciphertext, it is vulnerable topadding oracle attacks that can let an attacker recover the plaintext.
funcEncryptPEMBlockdeprecatedadded ingo1.1
func EncryptPEMBlock(randio.Reader, blockTypestring, data, password []byte, algPEMCipher) (*pem.Block,error)
EncryptPEMBlock returns a PEM block of the specified type holding thegiven DER encoded data encrypted with the specified algorithm andpassword according toRFC 1423.
Deprecated: Legacy PEM encryption as specified inRFC 1423 is insecure bydesign. Since it does not authenticate the ciphertext, it is vulnerable topadding oracle attacks that can let an attacker recover the plaintext.
funcIsEncryptedPEMBlockdeprecatedadded ingo1.1
IsEncryptedPEMBlock returns whether the PEM block is password encryptedaccording toRFC 1423.
Deprecated: Legacy PEM encryption as specified inRFC 1423 is insecure bydesign. Since it does not authenticate the ciphertext, it is vulnerable topadding oracle attacks that can let an attacker recover the plaintext.
funcMarshalECPrivateKey¶added ingo1.2
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, useMarshalPKCS8PrivateKey.
funcMarshalPKCS1PrivateKey¶
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
MarshalPKCS1PrivateKey converts anRSA 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 notRSA specific, useMarshalPKCS8PrivateKey.
The key must have passed validation by callingrsa.PrivateKey.Validatefirst. MarshalPKCS1PrivateKey callsrsa.PrivateKey.Precompute, which maymodify the key if not already precomputed.
funcMarshalPKCS1PublicKey¶added ingo1.10
MarshalPKCS1PublicKey converts anRSA public key to PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
funcMarshalPKCS8PrivateKey¶added ingo1.10
MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.
The following key types are currently supported: *rsa.PrivateKey,*ecdsa.PrivateKey,ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey.Unsupported key types result in an error.
This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
MarshalPKCS8PrivateKey runsrsa.PrivateKey.Precompute on RSA keys.
funcMarshalPKIXPublicKey¶
MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.The encoded public key is a SubjectPublicKeyInfo structure(seeRFC 5280, Section 4.1).
The following key types are currently supported: *rsa.PublicKey,*ecdsa.PublicKey,ed25519.PublicKey (not a pointer), and *ecdh.PublicKey.Unsupported key types result in an error.
This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
funcParseCRLdeprecated
func ParseCRL(crlBytes []byte) (*pkix.CertificateList,error)
ParseCRL parses a CRL from the given bytes. It's often the case that PEMencoded CRLs will appear where they should be DER encoded, so this functionwill transparently handle PEM encoding as long as there isn't any leadinggarbage.
Deprecated: UseParseRevocationList instead.
funcParseDERCRLdeprecated
func ParseDERCRL(derBytes []byte) (*pkix.CertificateList,error)
ParseDERCRL parses a DER encoded CRL from the given bytes.
Deprecated: UseParseRevocationList instead.
funcParseECPrivateKey¶added ingo1.1
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".
funcParsePKCS1PrivateKey¶
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey,error)
ParsePKCS1PrivateKey parses anRSA private key in PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
Before Go 1.24, the CRT parameters were ignored and recomputed. To restorethe old behavior, use the GODEBUG=x509rsacrt=0 environment variable.
funcParsePKCS1PublicKey¶added ingo1.10
ParsePKCS1PublicKey parses anRSA public key in PKCS #1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
funcParsePKCS8PrivateKey¶
ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.
It returns a *rsa.PrivateKey, an *ecdsa.PrivateKey, aned25519.PrivateKey (nota pointer), or an *ecdh.PrivateKey (for X25519). More types might be supportedin the future.
This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
Before Go 1.24, the CRT parameters of RSA keys were ignored and recomputed.To restore the old behavior, use the GODEBUG=x509rsacrt=0 environment variable.
funcParsePKIXPublicKey¶
ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encodedpublic key is a SubjectPublicKeyInfo structure (seeRFC 5280, Section 4.1).
It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519).More types might be supported in the future.
This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
Example¶
package mainimport ("crypto/dsa""crypto/ecdsa""crypto/ed25519""crypto/rsa""crypto/x509""encoding/pem""fmt")func main() {const pubPEM = `-----BEGIN PUBLIC KEY-----MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbtyWPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/xqhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixYnP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/qTbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJyecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUkAIU+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")}}funcSetFallbackRoots¶added ingo1.20
func SetFallbackRoots(roots *CertPool)
SetFallbackRoots sets the roots to use during certificate verification, if nocustom roots are specified and a platform verifier or a system certificatepool is not available (for instance in a container which does not have a rootcertificate bundle). SetFallbackRoots will panic if roots is nil.
SetFallbackRoots may only be called once, if called multiple times it willpanic.
The fallback behavior can be forced on all platforms, even when there is asystem certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note thaton Windows and macOS this will disable usage of the platform verificationAPIs and cause the pure Go verifier to be used). Settingx509usefallbackroots=1 without calling SetFallbackRoots has no effect.
Types¶
typeCertPool¶
type CertPool struct {// contains filtered or unexported fields}CertPool is a set of certificates.
funcSystemCertPool¶added ingo1.7
SystemCertPool returns a copy of the system cert pool.
On Unix systems other than macOS the environment variables SSL_CERT_FILE andSSL_CERT_DIR can be used to override the system default locations for the SSLcertificate file and SSL certificate files directory, respectively. Thelatter can be a colon-separated list.
Any mutations to the returned pool are not written to disk and do not affectany 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)AddCertWithConstraint¶added ingo1.22.0
func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate)error)
AddCertWithConstraint adds a certificate to the pool with the additionalconstraint. When Certificate.Verify builds a chain which is rooted by cert,it will additionally pass the whole chain to constraint to determine itsvalidity. If constraint returns a non-nil error, the chain will be discarded.constraint may be called concurrently from multiple goroutines.
func (*CertPool)AppendCertsFromPEM¶
AppendCertsFromPEM attempts to parse a series of PEM encoded certificates.It appends any certificates found to s and reports whether any certificateswere successfully parsed.
On many Linux systems, /etc/ssl/cert.pem will contain the system wide setof root CAs in a format suitable for this function.
func (*CertPool)Subjectsdeprecated
Subjects returns a list of the DER-encoded subjects ofall of the certificates in the pool.
Deprecated: if s was returned bySystemCertPool, Subjectswill not include the system roots.
typeCertificate¶
type Certificate struct {Raw []byte// Complete ASN.1 DER content (certificate, signature algorithm and signature).RawTBSCertificate []byte// Certificate part of raw ASN.1 DER content.RawSubjectPublicKeyInfo []byte// DER encoded SubjectPublicKeyInfo.RawSubject []byte// DER encoded SubjectRawIssuer []byte// DER encoded IssuerSignature []byteSignatureAlgorithmSignatureAlgorithmPublicKeyAlgorithmPublicKeyAlgorithmPublicKeyanyVersionintSerialNumber *big.IntIssuerpkix.NameSubjectpkix.NameNotBefore, NotAftertime.Time// Validity bounds.KeyUsageKeyUsage// 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.ObjectIdentifierExtKeyUsage []ExtKeyUsage// Sequence of extended key usages.UnknownExtKeyUsage []asn1.ObjectIdentifier// Encountered extended key usages unknown to this package.// BasicConstraintsValid indicates whether IsCA, MaxPathLen,// and MaxPathLenZero are valid.BasicConstraintsValidboolIsCAbool// 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.MaxPathLenint// 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.MaxPathLenZeroboolSubjectKeyId []byteAuthorityKeyId []byte//RFC 5280, 4.2.2.1 (Authority Information Access)OCSPServer []stringIssuingCertificateURL []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.)DNSNames []stringEmailAddresses []stringIPAddresses []net.IPURIs []*url.URL// Name constraintsPermittedDNSDomainsCriticalbool// if true then the name constraints are marked critical.PermittedDNSDomains []stringExcludedDNSDomains []stringPermittedIPRanges []*net.IPNetExcludedIPRanges []*net.IPNetPermittedEmailAddresses []stringExcludedEmailAddresses []stringPermittedURIDomains []stringExcludedURIDomains []string// CRL Distribution PointsCRLDistributionPoints []string// PolicyIdentifiers contains asn1.ObjectIdentifiers, the components// of which are limited to int32. If a certificate contains a policy which// cannot be represented by asn1.ObjectIdentifier, it will not be included in// PolicyIdentifiers, but will be present in Policies, which contains all parsed// policy OIDs.// See CreateCertificate for context about how this field and the Policies field// interact.PolicyIdentifiers []asn1.ObjectIdentifier// Policies contains all policy identifiers included in the certificate.// See CreateCertificate for context about how this field and the PolicyIdentifiers field// interact.// In Go 1.22, encoding/gob cannot handle and ignores this field.Policies []OID// InhibitAnyPolicy and InhibitAnyPolicyZero indicate the presence and value// of the inhibitAnyPolicy extension.//// The value of InhibitAnyPolicy indicates the number of additional// certificates in the path after this certificate that may use the// anyPolicy policy OID to indicate a match with any other policy.//// When parsing a certificate, a positive non-zero InhibitAnyPolicy means// that the field was specified, -1 means it was unset, and// InhibitAnyPolicyZero being true mean that the field was explicitly set to// zero. The case of InhibitAnyPolicy==0 with InhibitAnyPolicyZero==false// should be treated equivalent to -1 (unset).InhibitAnyPolicyint// InhibitAnyPolicyZero indicates that InhibitAnyPolicy==0 should be// interpreted as an actual maximum path length of zero. Otherwise, that// combination is interpreted as InhibitAnyPolicy not being set.InhibitAnyPolicyZerobool// InhibitPolicyMapping and InhibitPolicyMappingZero indicate the presence// and value of the inhibitPolicyMapping field of the policyConstraints// extension.//// The value of InhibitPolicyMapping indicates the number of additional// certificates in the path after this certificate that may use policy// mapping.//// When parsing a certificate, a positive non-zero InhibitPolicyMapping// means that the field was specified, -1 means it was unset, and// InhibitPolicyMappingZero being true mean that the field was explicitly// set to zero. The case of InhibitPolicyMapping==0 with// InhibitPolicyMappingZero==false should be treated equivalent to -1// (unset).InhibitPolicyMappingint// InhibitPolicyMappingZero indicates that InhibitPolicyMapping==0 should be// interpreted as an actual maximum path length of zero. Otherwise, that// combination is interpreted as InhibitAnyPolicy not being set.InhibitPolicyMappingZerobool// RequireExplicitPolicy and RequireExplicitPolicyZero indicate the presence// and value of the requireExplicitPolicy field of the policyConstraints// extension.//// The value of RequireExplicitPolicy indicates the number of additional// certificates in the path after this certificate before an explicit policy// is required for the rest of the path. When an explicit policy is required,// each subsequent certificate in the path must contain a required policy OID,// or a policy OID which has been declared as equivalent through the policy// mapping extension.//// When parsing a certificate, a positive non-zero RequireExplicitPolicy// means that the field was specified, -1 means it was unset, and// RequireExplicitPolicyZero being true mean that the field was explicitly// set to zero. The case of RequireExplicitPolicy==0 with// RequireExplicitPolicyZero==false should be treated equivalent to -1// (unset).RequireExplicitPolicyint// RequireExplicitPolicyZero indicates that RequireExplicitPolicy==0 should be// interpreted as an actual maximum path length of zero. Otherwise, that// combination is interpreted as InhibitAnyPolicy not being set.RequireExplicitPolicyZerobool// PolicyMappings contains a list of policy mappings included in the certificate.PolicyMappings []PolicyMapping}A Certificate represents an X.509 certificate.
funcParseCertificate¶
func ParseCertificate(der []byte) (*Certificate,error)
ParseCertificate parses a single certificate from the given ASN.1 DER data.
Before Go 1.23, ParseCertificate accepted certificates with negative serialnumbers. This behavior can be restored by including "x509negativeserial=1" inthe GODEBUG environment variable.
funcParseCertificates¶
func ParseCertificates(der []byte) ([]*Certificate,error)
ParseCertificates parses one or more certificates from the given ASN.1 DERdata. The certificates must be concatenated with no intermediate padding.
func (*Certificate)CheckCRLSignaturedeprecated
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList)error
CheckCRLSignature checks that the signature in crl is from c.
Deprecated: UseRevocationList.CheckSignatureFrom instead.
func (*Certificate)CheckSignature¶
func (c *Certificate) CheckSignature(algoSignatureAlgorithm, signed, signature []byte)error
CheckSignature verifies that signature is a valid signature over signed fromc's public key.
This is a low-level API that performs no validity checks on the certificate.
MD5WithRSA signatures are rejected, whileSHA1WithRSA andECDSAWithSHA1signatures are currently accepted.
func (*Certificate)CheckSignatureFrom¶
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 fullpath verifier. Most users should useCertificate.Verify instead.
func (*Certificate)CreateCRLdeprecated
func (c *Certificate) CreateCRL(randio.Reader, privany, revokedCerts []pkix.RevokedCertificate, now, expirytime.Time) (crlBytes []byte, errerror)
CreateCRL returns a DER encoded CRL, signed by this Certificate, thatcontains the given list of revoked certificates.
Deprecated: this method does not generate anRFC 5280 conformant X.509 v2 CRL.To generate a standards compliant CRL, useCreateRevocationList instead.
func (*Certificate)Equal¶
func (c *Certificate) Equal(other *Certificate)bool
func (*Certificate)Verify¶
func (c *Certificate) Verify(optsVerifyOptions) (chains [][]*Certificate, errerror)
Verify attempts to verify c by building one or more chains from c to acertificate in opts.Roots, using certificates in opts.Intermediates ifneeded. If successful, it returns one or more chains where the firstelement of the chain is c and the last element is from opts.Roots.
If opts.Roots is nil, the platform verifier might be used, andverification details might differ from what is described below. If systemroots are unavailable the returned error will be of type SystemRootsError.
Name constraints in the intermediates will be applied to all names claimedin the chain, not just opts.DNSName. Thus it is invalid for a leaf to claimexample.com if an intermediate doesn't permit it, even if example.com is notthe name being validated. Note that DirectoryName constraints are notsupported.
Name constraint validation follows the rules fromRFC 5280, with theaddition that DNS name constraints may use the leading period formatdefined for emails and URIs. When a constraint has a leading periodit indicates that at least one additional label must be prepended tothe constrained name to be considered valid.
Extended Key Usage values are enforced nested down a chain, so an intermediateor root that enumerates EKUs prevents a leaf from asserting an EKU not in thatlist. (While this is not specified, it is common practice in order to limitthe types of certificates a CA can issue.)
Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not supported,and will not be used to build chains.
Certificates other than c in the returned chains should not be modified.
WARNING: this function doesn't do any revocation checking.
Example¶
package mainimport ("crypto/x509""encoding/pem")func main() {// Verifying with a custom list of root certificates.const rootPEM = `-----BEGIN CERTIFICATE-----MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQGEwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVybmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NPVaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtvh8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rEahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZEASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXCDTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2gK4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5nZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEBBQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjzaHFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwstoWHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx-----END CERTIFICATE-----`const certPEM = `-----BEGIN CERTIFICATE-----MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UEBhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRlcm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAwWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFpbC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAaBgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUFBwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcyLmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2NzcDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisGAQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoWRvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOhyE+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())}}func (*Certificate)VerifyHostname¶
func (c *Certificate) VerifyHostname(hstring)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 checkedagainst the IPAddresses field. Other names are checked case insensitivelyagainst the DNSNames field. If the names are valid hostnames, the certificatefields can have a wildcard as the complete left-most label (e.g. *.example.com).
Note that the legacy Common Name field is ignored.
typeCertificateInvalidError¶
type CertificateInvalidError struct {Cert *CertificateReasonInvalidReasonDetailstring}CertificateInvalidError results when an odd error occurs. Users of thislibrary probably want to handle all these errors uniformly.
func (CertificateInvalidError)Error¶
func (eCertificateInvalidError) Error()string
typeCertificateRequest¶added ingo1.3
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.VersionintSignature []byteSignatureAlgorithmSignatureAlgorithmPublicKeyAlgorithmPublicKeyAlgorithmPublicKeyanySubjectpkix.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.DNSNames []stringEmailAddresses []stringIPAddresses []net.IPURIs []*url.URL}CertificateRequest represents a PKCS #10, certificate signature request.
funcParseCertificateRequest¶added ingo1.3
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest,error)
ParseCertificateRequest parses a single certificate request from thegiven ASN.1 DER data.
func (*CertificateRequest)CheckSignature¶added ingo1.5
func (c *CertificateRequest) CheckSignature()error
CheckSignature reports whether the signature on c is valid.
typeConstraintViolationError¶
type ConstraintViolationError struct{}ConstraintViolationError results when a requested usage is not permitted bya certificate. For example: checking a signature when the public key isn't acertificate signing key.
func (ConstraintViolationError)Error¶
func (ConstraintViolationError) Error()string
typeExtKeyUsage¶
type ExtKeyUsageint
ExtKeyUsage represents an extended set of actions that are valid for a given key.Each of the ExtKeyUsage* constants define a unique action.
const (ExtKeyUsageAnyExtKeyUsage =iotaExtKeyUsageServerAuthExtKeyUsageClientAuthExtKeyUsageCodeSigningExtKeyUsageEmailProtectionExtKeyUsageIPSECEndSystemExtKeyUsageIPSECTunnelExtKeyUsageIPSECUserExtKeyUsageTimeStampingExtKeyUsageOCSPSigningExtKeyUsageMicrosoftServerGatedCryptoExtKeyUsageNetscapeServerGatedCryptoExtKeyUsageMicrosoftCommercialCodeSigningExtKeyUsageMicrosoftKernelCodeSigning)
typeHostnameError¶
type HostnameError struct {Certificate *CertificateHoststring}HostnameError results when the set of authorized names doesn't match therequested name.
func (HostnameError)Error¶
func (hHostnameError) Error()string
typeInsecureAlgorithmError¶added ingo1.6
type InsecureAlgorithmErrorSignatureAlgorithm
An InsecureAlgorithmError indicates that theSignatureAlgorithm used togenerate the signature is not secure, and the signature has been rejected.
func (InsecureAlgorithmError)Error¶added ingo1.6
func (eInsecureAlgorithmError) Error()string
typeInvalidReason¶
type InvalidReasonint
const (// NotAuthorizedToSign results when a certificate is signed by another// which isn't marked as a CA certificate.NotAuthorizedToSignInvalidReason =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// NoValidChains results when there are no valid chains to return.NoValidChains)
typeKeyUsage¶
type KeyUsageint
KeyUsage represents the set of actions that are valid for a given key. It'sa bitmap of the KeyUsage* constants.
typeOID¶added ingo1.22.0
type OID struct {// contains filtered or unexported fields}An OID represents an ASN.1 OBJECT IDENTIFIER.
funcOIDFromInts¶added ingo1.22.0
OIDFromInts creates a new OID using ints, each integer is a separate component.
funcParseOID¶added ingo1.23.0
ParseOID parses a Object Identifier string, represented by ASCII numbers separated by dots.
func (OID)AppendBinary¶added ingo1.24.0
AppendBinary implementsencoding.BinaryAppender
func (OID)AppendText¶added ingo1.24.0
AppendText implementsencoding.TextAppender
func (OID)Equal¶added ingo1.22.0
Equal returns true when oid and other represents the same Object Identifier.
func (OID)EqualASN1OID¶added ingo1.22.0
func (oidOID) EqualASN1OID(otherasn1.ObjectIdentifier)bool
EqualASN1OID returns whether an OID equals an asn1.ObjectIdentifier. Ifasn1.ObjectIdentifier cannot represent the OID specified by oid, becausea component of OID requires more than 31 bits, it returns false.
func (OID)MarshalBinary¶added ingo1.23.0
MarshalBinary implementsencoding.BinaryMarshaler
func (OID)MarshalText¶added ingo1.23.0
MarshalText implementsencoding.TextMarshaler
func (OID)String¶added ingo1.22.0
Strings returns the string representation of the Object Identifier.
func (*OID)UnmarshalBinary¶added ingo1.23.0
UnmarshalBinary implementsencoding.BinaryUnmarshaler
func (*OID)UnmarshalText¶added ingo1.23.0
UnmarshalText implementsencoding.TextUnmarshaler
typePEMCipher¶added ingo1.1
type PEMCipherint
const (PEMCipherDES PEMCipherPEMCipher3DESPEMCipherAES128PEMCipherAES192PEMCipherAES256)
Possible values for the EncryptPEMBlock encryption algorithm.
typePolicyMapping¶added ingo1.24.0
type PolicyMapping struct {// IssuerDomainPolicy contains a policy OID the issuing certificate considers// equivalent to SubjectDomainPolicy in the subject certificate.IssuerDomainPolicyOID// SubjectDomainPolicy contains a OID the issuing certificate considers// equivalent to IssuerDomainPolicy in the subject certificate.SubjectDomainPolicyOID}PolicyMapping represents a policy mapping entry in the policyMappings extension.
typePublicKeyAlgorithm¶
type PublicKeyAlgorithmint
const (UnknownPublicKeyAlgorithmPublicKeyAlgorithm =iotaRSADSA// Only supported for parsing.ECDSAEd25519)
func (PublicKeyAlgorithm)String¶added ingo1.10
func (algoPublicKeyAlgorithm) String()string
typeRevocationList¶added ingo1.15
type RevocationList struct {// Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,// signatureAlgorithm, and signatureValue.)Raw []byte// RawTBSRevocationList contains just the tbsCertList portion of the ASN.1// DER.RawTBSRevocationList []byte// RawIssuer contains the DER encoded Issuer.RawIssuer []byte// Issuer contains the DN of the issuing certificate.Issuerpkix.Name// AuthorityKeyId is used to identify the public key associated with the// issuing certificate. It is populated from the authorityKeyIdentifier// extension when parsing a CRL. It is ignored when creating a CRL; the// extension is populated from the issuing certificate itself.AuthorityKeyId []byteSignature []byte// 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.SignatureAlgorithmSignatureAlgorithm// RevokedCertificateEntries represents the revokedCertificates sequence in// the CRL. It is used when creating a CRL and also populated when parsing a// CRL. When creating a CRL, it may be empty or nil, in which case the// revokedCertificates ASN.1 sequence will be omitted from the CRL entirely.RevokedCertificateEntries []RevocationListEntry// RevokedCertificates is used to populate the revokedCertificates// sequence in the CRL if RevokedCertificateEntries is empty. It may be empty// or nil, in which case an empty CRL will be created.//// Deprecated: Use RevokedCertificateEntries instead.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. It is also populated from the cRLNumber// extension when parsing a CRL.Number *big.Int// ThisUpdate is used to populate the thisUpdate field in the CRL, which// indicates the issuance date of the CRL.ThisUpdatetime.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.NextUpdatetime.Time// Extensions contains raw X.509 extensions. When creating a CRL,// the Extensions field is ignored, see ExtraExtensions.Extensions []pkix.Extension// ExtraExtensions contains any additional extensions to add directly to// the CRL.ExtraExtensions []pkix.Extension}RevocationList represents aCertificate Revocation List (CRL) as specifiedbyRFC 5280.
funcParseRevocationList¶added ingo1.19
func ParseRevocationList(der []byte) (*RevocationList,error)
ParseRevocationList parses a X509 v2Certificate Revocation List from the givenASN.1 DER data.
func (*RevocationList)CheckSignatureFrom¶added ingo1.19
func (rl *RevocationList) CheckSignatureFrom(parent *Certificate)error
CheckSignatureFrom verifies that the signature on rl is a valid signaturefrom issuer.
typeRevocationListEntry¶added ingo1.21.0
type RevocationListEntry struct {// Raw contains the raw bytes of the revokedCertificates entry. It is set when// parsing a CRL; it is ignored when generating a CRL.Raw []byte// SerialNumber represents the serial number of a revoked certificate. It is// both used when creating a CRL and populated when parsing a CRL. It must not// be nil.SerialNumber *big.Int// RevocationTime represents the time at which the certificate was revoked. It// is both used when creating a CRL and populated when parsing a CRL. It must// not be the zero time.RevocationTimetime.Time// ReasonCode represents the reason for revocation, using the integer enum// values specified inRFC 5280 Section 5.3.1. When creating a CRL, the zero// value will result in the reasonCode extension being omitted. When parsing a// CRL, the zero value may represent either the reasonCode extension being// absent (which implies the default revocation reason of 0/Unspecified), or// it may represent the reasonCode extension being present and explicitly// containing a value of 0/Unspecified (which should not happen according to// the DER encoding rules, but can and does happen anyway).ReasonCodeint// Extensions contains raw X.509 extensions. When parsing CRL entries,// this can be used to extract non-critical extensions that are not// parsed by this package. When marshaling CRL entries, the Extensions// field is ignored, see ExtraExtensions.Extensions []pkix.Extension// ExtraExtensions contains extensions to be copied, raw, into any// marshaled CRL entries. Values override any extensions that would// otherwise be produced based on the other fields. The ExtraExtensions// field is not populated when parsing CRL entries, see Extensions.ExtraExtensions []pkix.Extension}RevocationListEntry represents an entry in the revokedCertificatessequence of a CRL.
typeSignatureAlgorithm¶
type SignatureAlgorithmint
const (UnknownSignatureAlgorithmSignatureAlgorithm =iotaMD2WithRSA// Unsupported.MD5WithRSA// Only supported for signing, not verification.SHA1WithRSA// Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.SHA256WithRSASHA384WithRSASHA512WithRSADSAWithSHA1// Unsupported.DSAWithSHA256// Unsupported.ECDSAWithSHA1// Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.ECDSAWithSHA256ECDSAWithSHA384ECDSAWithSHA512SHA256WithRSAPSSSHA384WithRSAPSSSHA512WithRSAPSSPureEd25519)
func (SignatureAlgorithm)String¶added ingo1.6
func (algoSignatureAlgorithm) String()string
typeSystemRootsError¶added ingo1.1
type SystemRootsError struct {Errerror}SystemRootsError results when we fail to load the system root certificates.
func (SystemRootsError)Error¶added ingo1.1
func (seSystemRootsError) Error()string
func (SystemRootsError)Unwrap¶added ingo1.16
func (seSystemRootsError) Unwrap()error
typeUnhandledCriticalExtension¶
type UnhandledCriticalExtension struct{}func (UnhandledCriticalExtension)Error¶
func (hUnhandledCriticalExtension) Error()string
typeUnknownAuthorityError¶
type UnknownAuthorityError struct {Cert *Certificate// contains filtered or unexported fields}UnknownAuthorityError results when the certificate issuer is unknown
func (UnknownAuthorityError)Error¶
func (eUnknownAuthorityError) Error()string
typeVerifyOptions¶
type VerifyOptions struct {// DNSName, if set, is checked against the leaf certificate with// Certificate.VerifyHostname or the platform verifier.DNSNamestring// 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.CurrentTimetime.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.MaxConstraintComparisionsint// CertificatePolicies specifies which certificate policy OIDs are// acceptable during policy validation. An empty CertificatePolices// field implies any valid policy is acceptable.CertificatePolicies []OID// contains filtered or unexported fields}VerifyOptions contains parameters for Certificate.Verify.
Source Files¶
Directories¶
| Path | Synopsis |
|---|---|
internal | |
macos Package macOS provides cgo-less wrappers for Core Foundation and Security.framework, similarly to how package syscall provides access to libSystem.dylib. | Package macOS provides cgo-less wrappers for Core Foundation and Security.framework, similarly to how package syscall provides access to libSystem.dylib. |
Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP. | Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP. |