Most relevant values for AFI from: http://www.iana.org/assignments/address-family-numbers.
const ( IPv4AddressFamilyIndicator = uint16(1) IPv6AddressFamilyIndicator = uint16(2) )
OID values for CRL extensions (TBSCertList.Extensions), RFC 5280 s5.2.
var ( OIDExtensionCRLNumber = asn1.ObjectIdentifier{2, 5, 29, 20} OIDExtensionDeltaCRLIndicator = asn1.ObjectIdentifier{2, 5, 29, 27} OIDExtensionIssuingDistributionPoint = asn1.ObjectIdentifier{2, 5, 29, 28} )
OID values for CRL entry extensions (RevokedCertificate.Extensions), RFC 5280 s5.3
var ( OIDExtensionCRLReasons = asn1.ObjectIdentifier{2, 5, 29, 21} OIDExtensionInvalidityDate = asn1.ObjectIdentifier{2, 5, 29, 24} OIDExtensionCertificateIssuer = asn1.ObjectIdentifier{2, 5, 29, 29} )
RevocationReasonCode values.
var ( Unspecified = RevocationReasonCode(0) KeyCompromise = RevocationReasonCode(1) CACompromise = RevocationReasonCode(2) AffiliationChanged = RevocationReasonCode(3) Superseded = RevocationReasonCode(4) CessationOfOperation = RevocationReasonCode(5) CertificateHold = RevocationReasonCode(6) RemoveFromCRL = RevocationReasonCode(8) PrivilegeWithdrawn = RevocationReasonCode(9) AACompromise = RevocationReasonCode(10) )
RFC 3279, 2.3 Public Key Algorithms
pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
rsadsi(113549) pkcs(1) 1 }
rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
x9-57(10040) x9cm(4) 1 }
id-ecPublicKey OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
var ( OIDPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} OIDPublicKeyRSAESOAEP = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 7} OIDPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} OIDPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} OIDPublicKeyRSAObsolete = asn1.ObjectIdentifier{2, 5, 8, 1, 1} OIDPublicKeyEd25519 = oidSignatureEd25519 )
RFC 5480, 2.1.1.1. Named Curve
secp224r1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) certicom(132) curve(0) 33 } secp256r1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } secp384r1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) certicom(132) curve(0) 34 } secp521r1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) certicom(132) curve(0) 35 } secp192r1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 }
NB: secp256r1 is equivalent to prime256v1, secp192r1 is equivalent to ansix9p192r and prime192v1
var ( OIDNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} OIDNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} OIDNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} OIDNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} OIDNamedCurveP192 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 1} )
OID values for standard extensions from RFC 5280.
var ( OIDExtensionArc = asn1.ObjectIdentifier{2, 5, 29} // id-ce RFC5280 s4.2.1 OIDExtensionSubjectKeyId = asn1.ObjectIdentifier{2, 5, 29, 14} OIDExtensionKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 15} OIDExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37} OIDExtensionAuthorityKeyId = asn1.ObjectIdentifier{2, 5, 29, 35} OIDExtensionBasicConstraints = asn1.ObjectIdentifier{2, 5, 29, 19} OIDExtensionSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17} OIDExtensionCertificatePolicies = asn1.ObjectIdentifier{2, 5, 29, 32} OIDExtensionNameConstraints = asn1.ObjectIdentifier{2, 5, 29, 30} OIDExtensionCRLDistributionPoints = asn1.ObjectIdentifier{2, 5, 29, 31} OIDExtensionIssuerAltName = asn1.ObjectIdentifier{2, 5, 29, 18} OIDExtensionSubjectDirectoryAttributes = asn1.ObjectIdentifier{2, 5, 29, 9} OIDExtensionInhibitAnyPolicy = asn1.ObjectIdentifier{2, 5, 29, 54} OIDExtensionPolicyConstraints = asn1.ObjectIdentifier{2, 5, 29, 36} OIDExtensionPolicyMappings = asn1.ObjectIdentifier{2, 5, 29, 33} OIDExtensionFreshestCRL = asn1.ObjectIdentifier{2, 5, 29, 46} OIDExtensionAuthorityInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1} OIDExtensionSubjectInfoAccess = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 11} // OIDExtensionCTPoison is defined in RFC 6962 s3.1. OIDExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3} // OIDExtensionCTSCT is defined in RFC 6962 s3.3. OIDExtensionCTSCT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2} // OIDExtensionIPPrefixList is defined in RFC 3779 s2. OIDExtensionIPPrefixList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 7} // OIDExtensionASList is defined in RFC 3779 s3. OIDExtensionASList = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 8} )
var ( OIDAuthorityInfoAccessOCSP = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} OIDAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} OIDSubjectInfoAccessTimestamp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 3} OIDSubjectInfoAccessCARepo = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 5} OIDAnyPolicy = asn1.ObjectIdentifier{2, 5, 29, 32, 0} )
ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
IncorrectPasswordError is returned when an incorrect password is detected.
var IncorrectPasswordError = errors.New("x509: decryption password incorrect")
func BuildPrecertTBS(tbsData []byte, preIssuer *Certificate) ([]byte, error)
BuildPrecertTBS builds a Certificate Transparency pre-certificate (RFC 6962 s3.1) from the given DER-encoded TBSCertificate, returning a DER-encoded TBSCertificate.
This function removes the CT poison extension (there must be exactly 1 of these), preserving the order of other extensions.
If preIssuer is provided, this should be a special intermediate certificate that was used to sign the precert (indicated by having the special CertificateTransparency extended key usage). In this case, the issuance information of the pre-cert is updated to reflect the next issuer in the chain, i.e. the issuer of this special intermediate:
func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)
CreateCertificate creates a new X.509v3 certificate based on a template. The following members of template are used:
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 signee 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.
func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error)
CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:
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 DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
DecryptPEMBlock takes a password encrypted PEM block 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 encrypted-PEM format, it's not always possible to detect an incorrect password. In these cases no error will be returned but the decrypted DER bytes will be random noise.
func EncryptPEMBlock(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.
func IsEncryptedPEMBlock(b *pem.Block) bool
IsEncryptedPEMBlock returns if the PEM block is password encrypted.
func IsFatal(err error) bool
IsFatal indicates whether an error is fatal.
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(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(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(key interface{}) ([]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 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(pub interface{}) ([]byte, error)
MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
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 OIDFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool)
OIDFromNamedCurve returns the OID used to specify the use of the given elliptic curve.
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(derBytes []byte) (*pkix.CertificateList, error)
ParseDERCRL parses a DER encoded CRL from the given bytes.
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 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(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(der []byte) (key interface{}, err error)
ParsePKCS8PrivateKey parses an unencrypted private key in PKCS#8, ASN.1 DER form.
It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, or a ed25519.PrivateKey. More types might be supported in the future.
This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)
ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
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
func RemoveCTPoison(tbsData []byte) ([]byte, error)
RemoveCTPoison takes a DER-encoded TBSCertificate and removes the CT poison extension (preserving the order of other extensions), and returns the result still as a DER-encoded TBSCertificate. This function will fail if there is not exactly 1 CT poison extension present.
func RemoveSCTList(tbsData []byte) ([]byte, error)
RemoveSCTList takes a DER-encoded TBSCertificate and removes the CT SCT extension that contains the SCT list (preserving the order of other extensions), and returns the result still as a DER-encoded TBSCertificate. This function will fail if there is not exactly 1 CT SCT extension present.
ASIDRange describes an inclusive range of AS Identifiers (AS numbers or routing domain identifiers).
type ASIDRange struct { Min int Max int }
ASIdentifiers describes a collection of AS Identifiers (AS numbers or routing domain identifiers).
type ASIdentifiers struct { // InheritFromIssuer indicates that the set of AS identifiers should // be taken from the issuer's certificate. InheritFromIssuer bool // ASIDs holds AS identifiers if InheritFromIssuer is false. ASIDs []int // ASIDs holds AS identifier ranges (inclusive) if InheritFromIssuer is false. ASIDRanges []ASIDRange }
CertPool is a set of certificates.
type CertPool struct {
// contains filtered or unexported fields
}
func NewCertPool() *CertPool
NewCertPool returns a new, empty CertPool.
func SystemCertPool() (*CertPool, error)
SystemCertPool returns a copy of the system cert pool.
Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.
New changes in the system cert pool might not be reflected in subsequent calls.
func (s *CertPool) AddCert(cert *Certificate)
AddCert adds a certificate to a pool.
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 (s *CertPool) Subjects() [][]byte
Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.
A Certificate represents an X.509 certificate.
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 Subject RawIssuer []byte // DER encoded Issuer Signature []byte SignatureAlgorithm SignatureAlgorithm PublicKeyAlgorithm PublicKeyAlgorithm PublicKey interface{} Version int SerialNumber *big.Int Issuer pkix.Name Subject pkix.Name NotBefore, NotAfter time.Time // Validity bounds. KeyUsage KeyUsage // Extensions contains raw X.509 extensions. When parsing certificates, // this can be used to extract non-critical extensions that are not // parsed by this package. When marshaling certificates, the Extensions // field is ignored, see ExtraExtensions. Extensions []pkix.Extension // ExtraExtensions contains extensions to be copied, raw, into any // marshaled certificates. Values override any extensions that would // otherwise be produced based on the other fields. The ExtraExtensions // field is not populated when parsing certificates, see Extensions. ExtraExtensions []pkix.Extension // UnhandledCriticalExtensions contains a list of extension IDs that // were not (fully) processed when parsing. Verify will fail if this // slice is non-empty, unless verification is delegated to an OS // library which understands all the critical extensions. // // Users can access these extensions using Extensions and can remove // elements from this slice if they believe that they have been // handled. UnhandledCriticalExtensions []asn1.ObjectIdentifier ExtKeyUsage []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. BasicConstraintsValid bool IsCA bool // MaxPathLen and MaxPathLenZero indicate the presence and // value of the BasicConstraints' "pathLenConstraint". // // When parsing a certificate, a positive non-zero MaxPathLen // means that the field was specified, -1 means it was unset, // and MaxPathLenZero being true mean that the field was // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false // should be treated equivalent to -1 (unset). // // When generating a certificate, an unset pathLenConstraint // can be requested with either MaxPathLen == -1 or using the // zero value for both MaxPathLen and MaxPathLenZero. MaxPathLen int // MaxPathLenZero indicates that BasicConstraintsValid==true // and MaxPathLen==0 should be interpreted as an actual // maximum path length of zero. Otherwise, that combination is // interpreted as MaxPathLen not being set. MaxPathLenZero bool SubjectKeyId []byte AuthorityKeyId []byte // RFC 5280, 4.2.2.1 (Authority Information Access) OCSPServer []string IssuingCertificateURL []string // Subject Information Access SubjectTimestamps []string SubjectCARepositories []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 []string EmailAddresses []string IPAddresses []net.IP URIs []*url.URL // Name constraints PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. PermittedDNSDomains []string ExcludedDNSDomains []string PermittedIPRanges []*net.IPNet ExcludedIPRanges []*net.IPNet PermittedEmailAddresses []string ExcludedEmailAddresses []string PermittedURIDomains []string ExcludedURIDomains []string // CRL Distribution Points CRLDistributionPoints []string PolicyIdentifiers []asn1.ObjectIdentifier RPKIAddressRanges []*IPAddressFamilyBlocks RPKIASNumbers, RPKIRoutingDomainIDs *ASIdentifiers // Certificate Transparency SCT extension contents; this is a TLS-encoded // SignedCertificateTimestampList (RFC 6962 s3.3). RawSCT []byte SCTList SignedCertificateTimestampList }
func ParseCertificate(asn1Data []byte) (*Certificate, error)
ParseCertificate parses a single certificate from the given ASN.1 DER data. This function can return both a Certificate and an error (in which case the error will be of type NonFatalErrors).
func ParseCertificates(asn1Data []byte) ([]*Certificate, error)
ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding. This function can return both a slice of Certificate and an error (in which case the error will be of type NonFatalErrors).
func ParseTBSCertificate(asn1Data []byte) (*Certificate, error)
ParseTBSCertificate parses a single TBSCertificate from the given ASN.1 DER data. The parsed data is returned in a Certificate struct for ease of access.
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
CheckCRLSignature checks that the signature in crl is from c.
func (c *Certificate) CheckCertificateListSignature(crl *CertificateList) error
CheckCertificateListSignature checks that the signature in crl is from c.
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
CheckSignature verifies that signature is a valid signature over signed from c's public key.
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error
CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
CreateCRL returns a DER encoded CRL, signed by this Certificate, that contains the given list of revoked certificates.
func (c *Certificate) Equal(other *Certificate) bool
Equal indicates whether two Certificate objects are equal (by comparing their DER-encoded values).
func (c *Certificate) IsPrecertificate() bool
IsPrecertificate checks whether the certificate is a precertificate, by checking for the presence of the CT Poison extension.
func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.
If opts.Roots is nil and system roots are unavailable the returned error will be of type SystemRootsError.
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.
Extended Key Usage values are enforced down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list.
WARNING: this function doesn't do any revocation checking.
▹ Example
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.
CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.
type CertificateInvalidError struct { Cert *Certificate Reason InvalidReason Detail string }
func (e CertificateInvalidError) Error() string
CertificateList represents the ASN.1 structure of the same name from RFC 5280, s5.1. It has the same content as pkix.CertificateList, but the contents include parsed versions of any extensions.
type CertificateList struct { Raw asn1.RawContent TBSCertList TBSCertList SignatureAlgorithm pkix.AlgorithmIdentifier SignatureValue asn1.BitString }
func ParseCertificateList(clBytes []byte) (*CertificateList, error)
ParseCertificateList parses a CertificateList (e.g. 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 ParseCertificateListDER(derBytes []byte) (*CertificateList, error)
ParseCertificateListDER parses a DER encoded CertificateList from the given bytes. For non-fatal errors, this function returns both an error and a CertificateList object.
func (certList *CertificateList) ExpiredAt(now time.Time) bool
ExpiredAt reports whether now is past the expiry time of certList.
CertificateRequest represents a PKCS #10, certificate signature request.
type CertificateRequest struct { Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. RawSubject []byte // DER encoded Subject. Version int Signature []byte SignatureAlgorithm SignatureAlgorithm PublicKeyAlgorithm PublicKeyAlgorithm PublicKey interface{} Subject pkix.Name // Attributes contains the CSR attributes that can parse as // pkix.AttributeTypeAndValueSET. // // Deprecated: Use Extensions and ExtraExtensions instead for parsing and // generating the requestedExtensions attribute. Attributes []pkix.AttributeTypeAndValueSET // Extensions contains all requested extensions, in raw form. When parsing // CSRs, this can be used to extract extensions that are not parsed by this // package. Extensions []pkix.Extension // ExtraExtensions contains extensions to be copied, raw, into any CSR // marshaled by CreateCertificateRequest. Values override any extensions // that would otherwise be produced based on the other fields but are // overridden by any extensions specified in Attributes. // // The ExtraExtensions field is not populated by ParseCertificateRequest, // see Extensions instead. ExtraExtensions []pkix.Extension // Subject Alternate Name values. DNSNames []string EmailAddresses []string IPAddresses []net.IP URIs []*url.URL }
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.
func (c *CertificateRequest) CheckSignature() error
CheckSignature reports whether the signature on c is valid.
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.
type ConstraintViolationError struct{}
func (ConstraintViolationError) Error() string
ErrCategory indicates the category of an x509.Error.
type ErrCategory int
ErrCategory values.
const ( UnknownCategory ErrCategory = iota // Errors in ASN.1 encoding InvalidASN1Encoding InvalidASN1Content InvalidASN1DER // Errors in ASN.1 relative to schema InvalidValueRange InvalidASN1Type UnexpectedAdditionalData // Errors in X.509 PoorlyFormedCertificate // Fails a SHOULD clause MalformedCertificate // Fails a MUST clause PoorlyFormedCRL // Fails a SHOULD clause MalformedCRL // Fails a MUST clause // Errors relative to CA/Browser Forum guidelines BaselineRequirementsFailure EVRequirementsFailure // Other errors InsecureAlgorithm UnrecognizedValue )
func (category ErrCategory) String() string
Error implements the error interface and describes a single error in an X.509 certificate or CRL.
type Error struct { ID ErrorID Category ErrCategory Summary string Field string SpecRef string SpecText string // Fatal indicates that parsing has been aborted. Fatal bool }
func NewError(id ErrorID, args ...interface{}) Error
NewError builds a new x509.Error based on the template for the given id.
func (err Error) Error() string
func (err Error) VerboseError() string
VerboseError creates a more verbose error string, including spec details.
ErrorID is an identifier for an x509.Error, to allow filtering.
type ErrorID int
To preserve error IDs, only append to this list, never insert.
const ( ErrInvalidID ErrorID = iota ErrInvalidCertList ErrTrailingCertList ErrUnexpectedlyCriticalCertListExtension ErrUnexpectedlyNonCriticalCertListExtension ErrInvalidCertListAuthKeyID ErrTrailingCertListAuthKeyID ErrInvalidCertListIssuerAltName ErrInvalidCertListCRLNumber ErrTrailingCertListCRLNumber ErrNegativeCertListCRLNumber ErrInvalidCertListDeltaCRL ErrTrailingCertListDeltaCRL ErrNegativeCertListDeltaCRL ErrInvalidCertListIssuingDP ErrTrailingCertListIssuingDP ErrCertListIssuingDPMultipleTypes ErrCertListIssuingDPInvalidFullName ErrInvalidCertListFreshestCRL ErrInvalidCertListAuthInfoAccess ErrTrailingCertListAuthInfoAccess ErrUnhandledCriticalCertListExtension ErrUnexpectedlyCriticalRevokedCertExtension ErrUnexpectedlyNonCriticalRevokedCertExtension ErrInvalidRevocationReason ErrTrailingRevocationReason ErrInvalidRevocationInvalidityDate ErrTrailingRevocationInvalidityDate ErrInvalidRevocationIssuer ErrUnhandledCriticalRevokedCertExtension ErrMaxID )
func ErrorFilter(ignore string) []ErrorID
ErrorFilter builds a list of error IDs (suitable for use with Errors.Filter) from a comma-separated string.
Errors implements the error interface and holds a collection of errors found in a certificate or CRL.
type Errors struct { Errs []Error }
func (e *Errors) AddID(id ErrorID, args ...interface{})
AddID adds the Error identified by the given id to an x509.Errors.
func (e *Errors) Empty() bool
Empty indicates whether e has no errors.
func (e *Errors) Error() string
Error converts to a string.
func (e *Errors) Fatal() bool
Fatal indicates whether e includes a fatal error
func (e Errors) Filter(filtered []ErrorID) Errors
Filter creates a new Errors object with any entries from the filtered list of IDs removed.
func (e *Errors) FirstFatal() error
FirstFatal returns the first fatal error in e, or nil if there is no fatal error.
func (e *Errors) VerboseError() string
VerboseError creates a more verbose error string, including spec details.
ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.
type ExtKeyUsage int
ExtKeyUsage values:
const ( ExtKeyUsageAny ExtKeyUsage = iota ExtKeyUsageServerAuth ExtKeyUsageClientAuth ExtKeyUsageCodeSigning ExtKeyUsageEmailProtection ExtKeyUsageIPSECEndSystem ExtKeyUsageIPSECTunnel ExtKeyUsageIPSECUser ExtKeyUsageTimeStamping ExtKeyUsageOCSPSigning ExtKeyUsageMicrosoftServerGatedCrypto ExtKeyUsageNetscapeServerGatedCrypto ExtKeyUsageMicrosoftCommercialCodeSigning ExtKeyUsageMicrosoftKernelCodeSigning ExtKeyUsageCertificateTransparency )
GeneralNames holds a collection of names related to a certificate.
type GeneralNames struct { DNSNames []string EmailAddresses []string DirectoryNames []pkix.Name URIs []string IPNets []net.IPNet RegisteredIDs []asn1.ObjectIdentifier OtherNames []OtherName }
func (gn GeneralNames) Empty() bool
Empty indicates whether a GeneralNames object is empty.
func (gn GeneralNames) Len() int
Len returns the total number of names in a GeneralNames object.
HostnameError results when the set of authorized names doesn't match the requested name.
type HostnameError struct { Certificate *Certificate Host string }
func (h HostnameError) Error() string
IPAddressFamilyBlocks describes a set of ranges of IP addresses.
type IPAddressFamilyBlocks struct { // AFI holds an address family indicator from // http://www.iana.org/assignments/address-family-numbers. AFI uint16 // SAFI holds a subsequent address family indicator from // http://www.iana.org/assignments/safi-namespace. SAFI byte // InheritFromIssuer indicates that the set of addresses should // be taken from the issuer's certificate. InheritFromIssuer bool // AddressPrefixes holds prefixes if InheritFromIssuer is false. AddressPrefixes []IPAddressPrefix // AddressRanges holds ranges if InheritFromIssuer is false. AddressRanges []IPAddressRange }
IPAddressPrefix describes an IP address prefix as an ASN.1 bit string, where the BitLength field holds the prefix length.
type IPAddressPrefix asn1.BitString
IPAddressRange describes an (inclusive) IP address range.
type IPAddressRange struct { Min IPAddressPrefix Max IPAddressPrefix }
InsecureAlgorithmError results when the signature algorithm for a certificate is known to be insecure.
type InsecureAlgorithmError SignatureAlgorithm
func (e InsecureAlgorithmError) Error() string
type InvalidReason int
const ( // NotAuthorizedToSign results when a certificate is signed by another // which isn't marked as a CA certificate. NotAuthorizedToSign InvalidReason = iota // Expired results when a certificate has expired, based on the time // given in the VerifyOptions. Expired // CANotAuthorizedForThisName results when an intermediate or root // certificate has a name constraint which doesn't permit a DNS or // other name (including IP address) in the leaf certificate. CANotAuthorizedForThisName // TooManyIntermediates results when a path length constraint is // violated. TooManyIntermediates // IncompatibleUsage results when the certificate's key usage indicates // that it may only be used for a different purpose. IncompatibleUsage // NameMismatch results when the subject name of a parent certificate // does not match the issuer name in the child. NameMismatch // NameConstraintsWithoutSANs results when a leaf certificate doesn't // contain a Subject Alternative Name extension, but a CA certificate // contains name constraints, and the Common Name can be interpreted as // a hostname. // // You can avoid this error by setting the experimental GODEBUG environment // variable to "x509ignoreCN=1", disabling Common Name matching entirely. // This behavior might become the default in the future. 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 )
IssuingDistributionPoint represents the ASN.1 structure of the same name
type IssuingDistributionPoint struct { DistributionPoint distributionPointName `asn1:"optional,tag:0"` OnlyContainsUserCerts bool `asn1:"optional,tag:1"` OnlyContainsCACerts bool `asn1:"optional,tag:2"` OnlySomeReasons asn1.BitString `asn1:"optional,tag:3"` IndirectCRL bool `asn1:"optional,tag:4"` OnlyContainsAttributeCerts bool `asn1:"optional,tag:5"` }
KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.
type KeyUsage int
KeyUsage values:
const ( KeyUsageDigitalSignature KeyUsage = 1 << iota KeyUsageContentCommitment KeyUsageKeyEncipherment KeyUsageDataEncipherment KeyUsageKeyAgreement KeyUsageCertSign KeyUsageCRLSign KeyUsageEncipherOnly KeyUsageDecipherOnly )
NonFatalErrors is an error type which can hold a number of other errors. It's used to collect a range of non-fatal errors which occur while parsing a certificate, that way we can still match on certs which technically are invalid.
type NonFatalErrors struct { Errors []error }
func (e *NonFatalErrors) AddError(err error)
AddError adds an error to the list of errors contained by NonFatalErrors.
func (e *NonFatalErrors) Append(more *NonFatalErrors) *NonFatalErrors
Append combines the contents of two NonFatalErrors instances.
func (e NonFatalErrors) Error() string
Returns a string consisting of the values of Error() from all of the errors contained in |e|
func (e *NonFatalErrors) HasError() bool
HasError returns true if |e| contains at least one error
OtherName describes a name related to a certificate which is not in one of the standard name formats. RFC 5280, 4.2.1.6:
OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY DEFINED BY type-id }
type OtherName struct { TypeID asn1.ObjectIdentifier Value asn1.RawValue }
type PEMCipher int
Possible values for the EncryptPEMBlock encryption algorithm.
const ( PEMCipherDES PEMCipher PEMCipher3DES PEMCipherAES128 PEMCipherAES192 PEMCipherAES256 )
PublicKeyAlgorithm indicates the algorithm used for a certificate's public key.
type PublicKeyAlgorithm int
PublicKeyAlgorithm values:
const ( UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota RSA DSA ECDSA Ed25519 RSAESOAEP )
func (algo PublicKeyAlgorithm) String() string
ReasonFlag holds a bitmask of applicable revocation reasons, from RFC 5280 s4.2.1.13
type ReasonFlag int
ReasonFlag values.
const ( UnusedFlag ReasonFlag = 1 << iota KeyCompromiseFlag CACompromiseFlag AffiliationChangedFlag SupersededFlag CessationOfOperationFlag CertificateHoldFlag PrivilegeWithdrawnFlag AACompromiseFlag )
RevocationReasonCode represents the reason for a certificate revocation; see RFC 5280 s5.3.1.
type RevocationReasonCode asn1.Enumerated
RevokedCertificate represents the unnamed ASN.1 structure that makes up the revokedCertificates member of the TBSCertList structure from RFC 5280, s5.1. It has the same content as pkix.RevokedCertificate but the extensions are included in a parsed format.
type RevokedCertificate struct { pkix.RevokedCertificate // Cracked out extensions: RevocationReason RevocationReasonCode InvalidityDate time.Time Issuer GeneralNames }
SerializedSCT represents a single TLS-encoded signed certificate timestamp, from RFC6962 s3.3.
type SerializedSCT struct { Val []byte `tls:"minlen:1,maxlen:65535"` }
SignatureAlgorithm indicates the algorithm used to sign a certificate.
type SignatureAlgorithm int
SignatureAlgorithm values:
const ( UnknownSignatureAlgorithm SignatureAlgorithm = iota MD2WithRSA MD5WithRSA SHA1WithRSA SHA256WithRSA SHA384WithRSA SHA512WithRSA DSAWithSHA1 DSAWithSHA256 ECDSAWithSHA1 ECDSAWithSHA256 ECDSAWithSHA384 ECDSAWithSHA512 SHA256WithRSAPSS SHA384WithRSAPSS SHA512WithRSAPSS PureEd25519 )
func SignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm
SignatureAlgorithmFromAI converts an PKIX algorithm identifier to the equivalent local constant.
func (algo SignatureAlgorithm) String() string
SignedCertificateTimestampList is a list of signed certificate timestamps, from RFC6962 s3.3.
type SignedCertificateTimestampList struct { SCTList []SerializedSCT `tls:"minlen:1,maxlen:65335"` }
SystemRootsError results when we fail to load the system root certificates.
type SystemRootsError struct { Err error }
func (se SystemRootsError) Error() string
TBSCertList represents the ASN.1 structure of the same name from RFC 5280, section 5.1. It has the same content as pkix.TBSCertificateList but the extensions are included in a parsed format.
type TBSCertList struct { Raw asn1.RawContent Version int Signature pkix.AlgorithmIdentifier Issuer pkix.RDNSequence ThisUpdate time.Time NextUpdate time.Time RevokedCertificates []*RevokedCertificate Extensions []pkix.Extension // Cracked out extensions: AuthorityKeyID []byte IssuerAltNames GeneralNames CRLNumber int BaseCRLNumber int // -1 if no delta CRL present IssuingDistributionPoint IssuingDistributionPoint IssuingDPFullNames GeneralNames FreshestCRLDistributionPoint []string OCSPServer []string IssuingCertificateURL []string }
UnhandledCriticalExtension results when the certificate contains an extension that is marked as critical but which is not handled by this library.
type UnhandledCriticalExtension struct { ID asn1.ObjectIdentifier }
func (h UnhandledCriticalExtension) Error() string
UnknownAuthorityError results when the certificate issuer is unknown
type UnknownAuthorityError struct { Cert *Certificate // contains filtered or unexported fields }
func (e UnknownAuthorityError) Error() string
VerifyOptions contains parameters for Certificate.Verify. It's a structure because other PKIX verification APIs have ended up needing many options.
type VerifyOptions struct { DNSName string Intermediates *CertPool Roots *CertPool // if nil, the system roots are used CurrentTime time.Time // if zero, the current time is used // Options to disable various verification checks. DisableTimeChecks bool DisableCriticalExtensionChecks bool DisableNameChecks bool DisableEKUChecks bool DisablePathLenChecks bool DisableNameConstraintChecks bool // KeyUsage specifies which Extended Key Usage values are acceptable. A leaf // certificate is accepted if it contains any of the listed values. An empty // list means ExtKeyUsageServerAuth. To accept any key usage, include // ExtKeyUsageAny. // // Certificate chains are required to nest these extended key usage values. // (This matches the Windows CryptoAPI behavior, but not the spec.) 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. MaxConstraintComparisions int }