Involved Source Filescert_pool.gonotboring.goparser.gopem_decrypt.gopkcs1.gopkcs8.goroot.goroot_linux.goroot_unix.gosec1.goverify.go Package x509 implements a subset of the X.509 standard.
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 macOS and Windows, certificate verification is handled by system APIs, but
the package aims to apply consistent validation rules across operating
systems.
Code Examples
package main
import (
"crypto/x509"
"encoding/pem"
)
func main() {
// Verifying with a custom list of root certificates.
const rootPEM = `
-----BEGIN CERTIFICATE-----
MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
-----END CERTIFICATE-----`
const certPEM = `
-----BEGIN CERTIFICATE-----
MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
-----END CERTIFICATE-----`
// First, create the set of root certificates. For this example we only
// have one. It's also possible to omit this in order to use the
// default root set of the current operating system.
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
panic("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
panic("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic("failed to parse certificate: " + err.Error())
}
opts := x509.VerifyOptions{
DNSName: "mail.google.com",
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
panic("failed to verify certificate: " + err.Error())
}
}
package main
import (
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
)
func main() {
const pubPEM = `
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
-----END PUBLIC KEY-----`
block, _ := pem.Decode([]byte(pubPEM))
if block == nil {
panic("failed to parse PEM block containing the public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic("failed to parse DER encoded public key: " + err.Error())
}
switch pub := pub.(type) {
case *rsa.PublicKey:
fmt.Println("pub is of type RSA:", pub)
case *dsa.PublicKey:
fmt.Println("pub is of type DSA:", pub)
case *ecdsa.PublicKey:
fmt.Println("pub is of type ECDSA:", pub)
case ed25519.PublicKey:
fmt.Println("pub is of type Ed25519:", pub)
default:
panic("unknown type of public key")
}
}
Package-Level Type Names (total 45, in which 19 are exported)
/* sort exporteds by: | */
A Certificate represents an X.509 certificate.AuthorityKeyId[]byte BasicConstraintsValid indicates whether IsCA, MaxPathLen,
and MaxPathLenZero are valid. CRL Distribution Points 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.)EmailAddresses[]stringExcludedDNSDomains[]stringExcludedEmailAddresses[]stringExcludedIPRanges[]*net.IPNetExcludedURIDomains[]string // Sequence of extended key usages. 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. 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.IPAddresses[]net.IPIsCAboolIssuerpkix.NameIssuingCertificateURL[]stringKeyUsageKeyUsage 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. 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. // Validity bounds. // Validity bounds. RFC 5280, 4.2.2.1 (Authority Information Access)PermittedDNSDomains[]string Name constraints // if true then the name constraints are marked critical.PermittedEmailAddresses[]stringPermittedIPRanges[]*net.IPNetPermittedURIDomains[]stringPolicyIdentifiers[]asn1.ObjectIdentifierPublicKeyanyPublicKeyAlgorithmPublicKeyAlgorithm // Complete ASN.1 DER content (certificate, signature algorithm and signature). // DER encoded Issuer // DER encoded Subject // DER encoded SubjectPublicKeyInfo. // Certificate part of raw ASN.1 DER content.SerialNumber*big.IntSignature[]byteSignatureAlgorithmSignatureAlgorithmSubjectpkix.NameSubjectKeyId[]byteURIs[]*url.URL 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. // Encountered extended key usages unknown to this package.Versionint CheckCRLSignature checks that the signature in crl is from c.
Deprecated: Use RevocationList.CheckSignatureFrom instead. 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. 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. CreateCRL returns a DER encoded CRL, signed by this Certificate, that
contains the given list of revoked certificates.
Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
To generate a standards compliant CRL, use CreateRevocationList instead.(*Certificate) Equal(other *Certificate) bool 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 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. 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.(*Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error) checkNameConstraints checks that c permits a child certificate to claim the
given name, of type nameType. The argument parsedName contains the parsed
form of name, suitable for passing to the match function. The total number
of comparisons is tracked in the given count and should not exceed the given
limit.(*Certificate) getSANExtension() []byte(*Certificate) hasNameConstraints() bool(*Certificate) hasSANExtension() bool isValid performs validity checks on c given that it is a candidate to append
to the chain in currentChain.(*Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error)
func ParseCertificate(der []byte) (*Certificate, error)
func ParseCertificates(der []byte) ([]*Certificate, error)
func (*Certificate).Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate
func parseCertificate(der []byte) (*Certificate, error)
func (*Certificate).buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error)
func (*Certificate).systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error)
func (*CertPool).cert(n int) (*Certificate, error)
func (*CertPool).findPotentialParents(cert *Certificate) []*Certificate
func crypto/tls.(*Certificate).leaf() (*Certificate, error)
func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)
func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)
func (*Certificate).CheckSignatureFrom(parent *Certificate) error
func (*Certificate).Equal(other *Certificate) bool
func (*CertPool).AddCert(cert *Certificate)
func (*RevocationList).CheckSignatureFrom(parent *Certificate) error
func alreadyInChain(candidate *Certificate, chain []*Certificate) bool
func alreadyInChain(candidate *Certificate, chain []*Certificate) bool
func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate
func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate
func boringAllowCert(c *Certificate) bool
func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error)
func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool
func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error)
func processExtensions(out *Certificate) error
func subjectBytes(cert *Certificate) ([]byte, error)
func (*Certificate).buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error)
func (*Certificate).isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error
func (*CertPool).contains(cert *Certificate) bool
func (*CertPool).findPotentialParents(cert *Certificate) []*Certificate
func crypto/tls.certificatesToBytesSlice(certs []*Certificate) [][]byte
CertificateInvalidError results when an odd error occurs. Users of this
library probably want to handle all these errors uniformly.Cert*CertificateDetailstringReasonInvalidReason( CertificateInvalidError) Error() string
CertificateInvalidError : error
CertificateRequest represents a PKCS #10, certificate signature request. Attributes contains the CSR attributes that can parse as
pkix.AttributeTypeAndValueSET.
Deprecated: Use Extensions and ExtraExtensions instead for parsing and
generating the requestedExtensions attribute. Subject Alternate Name values.EmailAddresses[]string 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. 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.IPAddresses[]net.IPPublicKeyanyPublicKeyAlgorithmPublicKeyAlgorithm // Complete ASN.1 DER content (CSR, signature algorithm and signature). // DER encoded Subject. // DER encoded SubjectPublicKeyInfo. // Certificate request info part of raw ASN.1 DER content.Signature[]byteSignatureAlgorithmSignatureAlgorithmSubjectpkix.NameURIs[]*url.URLVersionint CheckSignature reports whether the signature on c is valid.
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error)
func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)
func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error)
CertPool is a set of certificates. // cert.RawSubject => index into lazyCerts haveSum maps from sum224(cert.Raw) to true. It's used only
for AddCert duplicate detection, to avoid CertPool.contains
calls in the AddCert path (because the contains method can
call getCert and otherwise negate savings from lazy getCert
funcs). lazyCerts contains funcs that return a certificate,
lazily parsing/decompressing it as needed. systemPool indicates whether this is a special pool derived from the
system roots. If it includes additional roots, it requires doing two
verifications, one using the roots provided by the caller, and one using
the system platform verifier. AddCert adds a certificate to a pool. 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. Clone returns a copy of s. Equal reports whether s and other are equal. 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. addCertFunc adds metadata about a certificate to a pool, along with
a func to fetch that certificate later when needed.
The rawSubject is Certificate.RawSubject and must be non-empty.
The getCert func may be called 0 or more times. cert returns cert index n in s.(*CertPool) contains(cert *Certificate) bool findPotentialParents returns the indexes of certificates in s which might
have signed cert. len returns the number of certs in the set.
A nil set is a valid empty set.
func NewCertPool() *CertPool
func SystemCertPool() (*CertPool, error)
func (*CertPool).Clone() *CertPool
func loadSystemRoots() (*CertPool, error)
func systemRootsPool() *CertPool
func SetFallbackRoots(roots *CertPool)
func (*CertPool).Equal(other *CertPool) bool
var systemRoots *CertPool
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.( ConstraintViolationError) Error() string
ConstraintViolationError : error
An InsecureAlgorithmError indicates that the SignatureAlgorithm used to
generate the signature is not secure, and the signature has been rejected.
To temporarily restore support for SHA-1 signatures, include the value
"x509sha1=1" in the GODEBUG environment variable. Note that this option will
be removed in a future release.( InsecureAlgorithmError) Error() string
InsecureAlgorithmError : error
RevocationList represents a Certificate Revocation List (CRL) as specified
by RFC 5280. 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. Extensions contains raw X.509 extensions. When creating a CRL,
the Extensions field is ignored, see ExtraExtensions. ExtraExtensions contains any additional extensions to add directly to
the CRL. Issuer contains the DN of the issuing certificate. 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. 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. Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
signatureAlgorithm, and signatureValue.) RawIssuer contains the DER encoded Issuer. RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
DER. 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. 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.Signature[]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. ThisUpdate is used to populate the thisUpdate field in the CRL, which
indicates the issuance date of the CRL. CheckSignatureFrom verifies that the signature on rl is a valid signature
from issuer.
func ParseRevocationList(der []byte) (*RevocationList, error)
func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)
RevocationListEntry represents an entry in the revokedCertificates
sequence of a CRL. 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. 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. Raw contains the raw bytes of the revokedCertificates entry. It is set when
parsing a CRL; it is ignored when generating a CRL. ReasonCode represents the reason for revocation, using the integer enum
values specified in RFC 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). 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. 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.
SystemRootsError results when we fail to load the system root certificates.Errerror( SystemRootsError) Error() string( SystemRootsError) Unwrap() error
SystemRootsError : error
SystemRootsError : github.com/go-faster/errors.Wrapper
UnknownAuthorityError results when the certificate issuer is unknownCert*Certificate hintCert contains a possible authority certificate that was rejected
because of the error in hintErr. hintErr contains an error that may be helpful in determining why an
authority wasn't found.( UnknownAuthorityError) Error() string
UnknownAuthorityError : error
VerifyOptions contains parameters for Certificate.Verify. CurrentTime is used to check the validity of all certificates in the
chain. If zero, the current time is used. DNSName, if set, is checked against the leaf certificate with
Certificate.VerifyHostname or the platform verifier. 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. 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. 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. 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.
func (*Certificate).Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
func (*Certificate).buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error)
func (*Certificate).isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error
func (*Certificate).systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error)
These structures reflect the ASN.1 structure of X.509 CRLs better than
the existing crypto/x509/pkix variants do. These mirror the existing
certificate structs in this file.
Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.SignatureAlgorithmpkix.AlgorithmIdentifierSignatureValueasn1.BitStringTBSCertListtbsCertificateList
lazyCert is minimal metadata about a Cert and a func to retrieve it
in its normal expanded *Certificate form. getCert returns the certificate.
It is not meant to do network operations or anything else
where a failure is likely; the func is meant to lazily
parse/decompress data that is already known to be good. The
error in the signature primarily is meant for use in the
case where a cert file existed on local disk when the program
started up is deleted later before it's read. rawSubject is the Certificate.RawSubject value.
It's the same as the CertPool.byName key, but in []byte
form to make CertPool.Subjects (as used by crypto/tls) do
fewer allocations.
pssParameters reflects the parameters in an AlgorithmIdentifier that
specifies RSA PSS. See RFC 3447, Appendix A.2.3. The following three fields are not marked as
optional because the default values specify SHA-1,
which is no longer suitable for use in signatures.MGFpkix.AlgorithmIdentifierSaltLengthintTrailerFieldint
Package-Level Functions (total 96, in which 25 are exported)
CreateCertificate creates a new X.509 v3 certificate based on a template.
The following members of template are currently used:
- AuthorityKeyId
- BasicConstraintsValid
- CRLDistributionPoints
- DNSNames
- EmailAddresses
- ExcludedDNSDomains
- ExcludedEmailAddresses
- ExcludedIPRanges
- ExcludedURIDomains
- ExtKeyUsage
- ExtraExtensions
- IPAddresses
- IsCA
- IssuingCertificateURL
- KeyUsage
- MaxPathLen
- MaxPathLenZero
- NotAfter
- NotBefore
- OCSPServer
- PermittedDNSDomains
- PermittedDNSDomainsCritical
- PermittedEmailAddresses
- PermittedIPRanges
- PermittedURIDomains
- PolicyIdentifiers
- SerialNumber
- SignatureAlgorithm
- Subject
- SubjectKeyId
- URIs
- UnknownExtKeyUsage
The certificate is signed by parent. If parent is equal to template then the
certificate is self-signed. The parameter pub is the public key of the
certificate to be generated and priv is the private key of the signer.
The returned slice is the certificate in DER encoding.
The currently supported key types are *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.
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.
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.
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.
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.
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.
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.
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.
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".
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".
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, 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".
NewCertPool returns a new, empty CertPool.
ParseCertificate parses a single certificate from the given ASN.1 DER data.
ParseCertificateRequest parses a single certificate request from the
given ASN.1 DER data.
ParseCertificates parses one or more certificates from the given ASN.1 DER
data. The certificates must be concatenated with no intermediate padding.
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.
Deprecated: Use ParseRevocationList instead.
ParseDERCRL parses a DER encoded CRL from the given bytes.
Deprecated: Use ParseRevocationList instead.
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".
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".
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".
ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.
It returns a *rsa.PrivateKey, an *ecdsa.PrivateKey, an ed25519.PrivateKey (not
a pointer), or an *ecdh.PrivateKey (for X25519). More types might be supported
in the future.
This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded
public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
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".
ParseRevocationList parses a X509 v2 Certificate Revocation List from the given
ASN.1 DER data.
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.
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.
alreadyInChain checks whether a candidate certificate is present in a chain.
Rather than doing a direct byte for byte equivalency check, we check if the
subject, public key, and SAN, if present, are equal. This prevents loops that
are created by mutual cross-signatures, or other cross-signature bridge
oddities.
asn1BitLength returns the bit-length of bitString by considering the
most-significant bit in a byte to be the "first" bit. This convention
matches ASN.1, but differs from almost everything else.
getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm
identifier for public key types supported in certificates and CSRs. Marshal
and Parse functions may support a different set of public key types.
parseASN1String parses the ASN.1 string types T61String, PrintableString,
UTF8String, BMPString, IA5String, and NumericString. This is mostly copied
from the respective encoding/asn1.parse... methods, rather than just
increasing the API surface of that package.
parseCSRExtensions parses the attributes from a CSR and extracts any
requested extensions.
parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
The OID for the named curve may be provided from another source (such as
the PKCS8 container) - if it is provided then use this instead of the OID
that may exist in the EC private key structure.
parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
parseRFC2821Mailbox parses an email address into local and domain parts,
based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
signingParamsForPublicKey returns the parameters to use for signing with
priv. If requestedSigAlgo is not zero then it overrides the default
signature algorithm.
toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use
an explicitly ASCII function to avoid any sharp corners resulting from
performing Unicode operations on DNS labels.
validHostname reports whether host is a valid hostname that can be matched or
matched against according to RFC 6125 2.2, with some leniency to accommodate
legacy values.
hashToPSSParameters contains the DER encoded RSA PSS parameters for the
SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
The parameters contain the following values:
- hashAlgorithm contains the associated hash identifier with NULL parameters
- maskGenAlgorithm always contains the default mgf1SHA1 identifier
- saltLength contains the length of the associated hash
- trailerField always contains the default trailerFieldBC value
oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
but it's specified by ISO. Microsoft's makecert.exe has been known
to produce certificates with this OID.
Package-Level Constants (total 72, in which 60 are exported)
CANotAuthorizedForExtKeyUsage results when an intermediate or root
certificate does not permit a requested extended key usage.
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.
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.
TooManyIntermediates results when a path length constraint is
violated.
UnconstrainedName results when a CA certificate contains permitted
name constraints, but leaf certificate contains a name of an
unsupported or unconstrained type.
certDirEnv is the environment variable which identifies which directory
to check for SSL certificate files. If set this overrides the system default.
It is a colon separated list of directories.
See https://www.openssl.org/docs/man1.0.2/man1/c_rehash.html.
certFileEnv is the environment variable which identifies where to locate
the SSL certificate file. If set this overrides the system default.
maxChainSignatureChecks is the maximum number of CheckSignatureFrom calls
that an invocation of buildChains will (transitively) make. Most chains are
less than 15 certificates long, so this leaves space for multiple chains and
for failed checks due to different intermediates having the same Subject.
The X.509 standards confusingly 1-indexed the version names, but 0-indexed
the actual encoded version, so the version for X.509v2 is 1.
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.