Documentation
¶
Overview ¶
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.
Index ¶
- Constants
- 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 FilterByDate(chains [][]*Certificate, now time.Time) (current, expired, never [][]*Certificate)
- func GetRSAPublicKeyJSON(key *rsa.PublicKey) *jsonKeys.RSAPublicKey
- 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 AuthorityInfoAccess
- type BasicConstraints
- type CABFOrganizationIDASN
- type CABFOrganizationIdentifier
- type CRLDistributionPoints
- 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) Certificates() []*Certificate
- func (s *CertPool) Clone() *CertPool
- func (s *CertPool) Contains(cert *Certificate) bool
- func (s *CertPool) Covers(pool *CertPool) bool
- func (s *CertPool) Equal(other *CertPool) bool
- func (s *CertPool) Size() int
- func (s *CertPool) Subjects() [][]bytedeprecated
- func (s *CertPool) Sum(other *CertPool) (sum *CertPool)
- type CertValidationLevel
- 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) CollectAllNames() []string
- 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) GetParsedDNSNames(invalidateCache bool) []ParsedDomainName
- func (c *Certificate) GetParsedSubjectCommonName(invalidateCache bool) ParsedDomainName
- func (c *Certificate) JsonifyExtensions() (*CertificateExtensions, UnknownCertificateExtensions)
- func (c *Certificate) MarshalJSON() ([]byte, error)
- func (c *Certificate) PublicKeyAlgorithmName() string
- func (c *Certificate) SignatureAlgorithmName() string
- func (c *Certificate) SubjectAndKey() *SubjectAndKey
- func (c *Certificate) UnmarshalJSON(b []byte) error
- func (c *Certificate) ValidateWithStupidDetail(opts VerifyOptions) (chains []CertificateChain, validation *Validation, err error)deprecated
- func (c *Certificate) Verify(opts VerifyOptions) (current, expired, never [][]*Certificate, err error)
- func (c *Certificate) VerifyHostname(h string) error
- type CertificateChain
- func (chain CertificateChain) AppendToFreshChain(c *Certificate) CertificateChain
- func (chain CertificateChain) CertificateInChain(c *Certificate) bool
- func (chain CertificateChain) CertificateSubjectAndKeyInChain(c *Certificate) bool
- func (chain CertificateChain) Range(f func(int, *Certificate))
- func (chain CertificateChain) SubjectAndKeyInChain(sk *SubjectAndKey) bool
- type CertificateExtensions
- type CertificateFingerprint
- type CertificateInvalidError
- type CertificatePolicies
- type CertificatePoliciesData
- type CertificatePoliciesJSON
- type CertificateRequest
- type CertificateType
- type ConstraintViolationError
- type DSAPublicKeyJSON
- type ECDSAPublicKeyJSON
- type ExtKeyUsage
- type ExtendedKeyUsage
- type ExtendedKeyUsageExtension
- type GeneralNames
- type GeneralSubtreeRaw
- type HostnameError
- type InsecureAlgorithmError
- type InvalidReason
- type IsPrecert
- type JSONCertificate
- type JSONCertificateWithRaw
- type JSONSignature
- type JSONSignatureAlgorithm
- type JSONSubjectKeyInfo
- type JSONValidity
- type KeyUsage
- type MonetaryValue
- type NameConstraints
- type NameConstraintsJSON
- type NoticeNumber
- type NoticeReference
- 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 PDSLocation
- type PDSLocations
- type PEMCipher
- type ParsedDomainName
- type ParsedQCStatements
- type PublicKeyAlgorithm
- type QCLegistation
- type QCStatementASN
- type QCStatements
- type QCStatementsASN
- type QCType
- type RevocationList
- type RevocationListEntry
- type SignatureAlgorithm
- type SignatureAlgorithmOID
- type SubjAuthKeyId
- type SubjectAndKey
- type SystemRootsError
- type TorServiceDescriptorHash
- type UnhandledCriticalExtension
- type UnknownAuthorityError
- type UnknownCertificateExtensions
- type UserNotice
- type UserNoticeData
- type Validation
- type VerifyOptions
- type X25519PublicKey
Examples ¶
Constants ¶
const ( OID_EKU_APPLE_CODE_SIGNING = "1.2.840.113635.100.4.1" OID_EKU_APPLE_CODE_SIGNING_DEVELOPMENT = "1.2.840.113635.100.4.1.1" OID_EKU_APPLE_SOFTWARE_UPDATE_SIGNING = "1.2.840.113635.100.4.1.2" OID_EKU_APPLE_CODE_SIGNING_THIRD_PARTY = "1.2.840.113635.100.4.1.3" OID_EKU_APPLE_RESOURCE_SIGNING = "1.2.840.113635.100.4.1.4" OID_EKU_APPLE_ICHAT_SIGNING = "1.2.840.113635.100.4.2" OID_EKU_APPLE_ICHAT_ENCRYPTION = "1.2.840.113635.100.4.3" OID_EKU_APPLE_SYSTEM_IDENTITY = "1.2.840.113635.100.4.4" OID_EKU_APPLE_CRYPTO_ENV = "1.2.840.113635.100.4.5" OID_EKU_APPLE_CRYPTO_PRODUCTION_ENV = "1.2.840.113635.100.4.5.1" OID_EKU_APPLE_CRYPTO_MAINTENANCE_ENV = "1.2.840.113635.100.4.5.2" OID_EKU_APPLE_CRYPTO_TEST_ENV = "1.2.840.113635.100.4.5.3" OID_EKU_APPLE_CRYPTO_DEVELOPMENT_ENV = "1.2.840.113635.100.4.5.4" OID_EKU_APPLE_CRYPTO_QOS = "1.2.840.113635.100.4.6" OID_EKU_APPLE_CRYPTO_TIER0_QOS = "1.2.840.113635.100.4.6.1" OID_EKU_APPLE_CRYPTO_TIER1_QOS = "1.2.840.113635.100.4.6.2" OID_EKU_APPLE_CRYPTO_TIER2_QOS = "1.2.840.113635.100.4.6.3" OID_EKU_APPLE_CRYPTO_TIER3_QOS = "1.2.840.113635.100.4.6.4" OID_EKU_MICROSOFT_CERT_TRUST_LIST_SIGNING = "1.3.6.1.4.1.311.10.3.1" OID_EKU_MICROSOFT_QUALIFIED_SUBORDINATE = "1.3.6.1.4.1.311.10.3.10" OID_EKU_MICROSOFT_KEY_RECOVERY_3 = "1.3.6.1.4.1.311.10.3.11" OID_EKU_MICROSOFT_DOCUMENT_SIGNING = "1.3.6.1.4.1.311.10.3.12" OID_EKU_MICROSOFT_LIFETIME_SIGNING = "1.3.6.1.4.1.311.10.3.13" OID_EKU_MICROSOFT_MOBILE_DEVICE_SOFTWARE = "1.3.6.1.4.1.311.10.3.14" OID_EKU_MICROSOFT_SMART_DISPLAY = "1.3.6.1.4.1.311.10.3.15" OID_EKU_MICROSOFT_CSP_SIGNATURE = "1.3.6.1.4.1.311.10.3.16" OID_EKU_MICROSOFT_TIMESTAMP_SIGNING = "1.3.6.1.4.1.311.10.3.2" OID_EKU_MICROSOFT_SERVER_GATED_CRYPTO = "1.3.6.1.4.1.311.10.3.3" OID_EKU_MICROSOFT_SGC_SERIALIZED = "1.3.6.1.4.1.311.10.3.3.1" OID_EKU_MICROSOFT_ENCRYPTED_FILE_SYSTEM = "1.3.6.1.4.1.311.10.3.4" OID_EKU_MICROSOFT_EFS_RECOVERY = "1.3.6.1.4.1.311.10.3.4.1" OID_EKU_MICROSOFT_WHQL_CRYPTO = "1.3.6.1.4.1.311.10.3.5" OID_EKU_MICROSOFT_NT5_CRYPTO = "1.3.6.1.4.1.311.10.3.6" OID_EKU_MICROSOFT_OEM_WHQL_CRYPTO = "1.3.6.1.4.1.311.10.3.7" OID_EKU_MICROSOFT_EMBEDDED_NT_CRYPTO = "1.3.6.1.4.1.311.10.3.8" OID_EKU_MICROSOFT_ROOT_LIST_SIGNER = "1.3.6.1.4.1.311.10.3.9" OID_EKU_MICROSOFT_DRM = "1.3.6.1.4.1.311.10.5.1" OID_EKU_MICROSOFT_DRM_INDIVIDUALIZATION = "1.3.6.1.4.1.311.10.5.2" OID_EKU_MICROSOFT_LICENSES = "1.3.6.1.4.1.311.10.5.3" OID_EKU_MICROSOFT_LICENSE_SERVER = "1.3.6.1.4.1.311.10.5.4" OID_EKU_MICROSOFT_ENROLLMENT_AGENT = "1.3.6.1.4.1.311.20.2.1" OID_EKU_MICROSOFT_SMARTCARD_LOGON = "1.3.6.1.4.1.311.20.2.2" OID_EKU_MICROSOFT_CA_EXCHANGE = "1.3.6.1.4.1.311.21.5" OID_EKU_MICROSOFT_KEY_RECOVERY_21 = "1.3.6.1.4.1.311.21.6" OID_EKU_MICROSOFT_SYSTEM_HEALTH = "1.3.6.1.4.1.311.47.1.1" OID_EKU_MICROSOFT_SYSTEM_HEALTH_LOOPHOLE = "1.3.6.1.4.1.311.47.1.3" OID_EKU_MICROSOFT_KERNEL_MODE_CODE_SIGNING = "1.3.6.1.4.1.311.61.1.1" OID_EKU_SERVER_AUTH = "1.3.6.1.5.5.7.3.1" OID_EKU_DVCS = "1.3.6.1.5.5.7.3.10" OID_EKU_SBGP_CERT_AA_SERVICE_AUTH = "1.3.6.1.5.5.7.3.11" OID_EKU_EAP_OVER_PPP = "1.3.6.1.5.5.7.3.13" OID_EKU_EAP_OVER_LAN = "1.3.6.1.5.5.7.3.14" OID_EKU_CLIENT_AUTH = "1.3.6.1.5.5.7.3.2" OID_EKU_CODE_SIGNING = "1.3.6.1.5.5.7.3.3" OID_EKU_EMAIL_PROTECTION = "1.3.6.1.5.5.7.3.4" OID_EKU_IPSEC_END_SYSTEM = "1.3.6.1.5.5.7.3.5" OID_EKU_IPSEC_TUNNEL = "1.3.6.1.5.5.7.3.6" OID_EKU_IPSEC_USER = "1.3.6.1.5.5.7.3.7" OID_EKU_TIME_STAMPING = "1.3.6.1.5.5.7.3.8" OID_EKU_OCSP_SIGNING = "1.3.6.1.5.5.7.3.9" OID_EKU_IPSEC_INTERMEDIATE_SYSTEM_USAGE = "1.3.6.1.5.5.8.2.2" OID_EKU_NETSCAPE_SERVER_GATED_CRYPTO = "2.16.840.1.113730.4.1" OID_EKU_ANY = "2.5.29.37.0" )
Variables ¶
var DomainValidationOIDs = map[string]interface{}{ "1.3.6.1.4.1.4146.1.10.10": nil, "1.3.6.1.4.1.44947.1.1.1": nil, "1.3.6.1.4.1.6449.1.2.2.10": nil, "1.3.6.1.4.1.6449.1.2.2.15": nil, "1.3.6.1.4.1.6449.1.2.2.16": nil, "1.3.6.1.4.1.6449.1.2.2.17": nil, "1.3.6.1.4.1.6449.1.2.2.18": nil, "1.3.6.1.4.1.6449.1.2.2.19": nil, "1.3.6.1.4.1.6449.1.2.2.21": nil, "1.3.6.1.4.1.6449.1.2.2.22": nil, "1.3.6.1.4.1.6449.1.2.2.24": nil, "1.3.6.1.4.1.6449.1.2.2.25": nil, "1.3.6.1.4.1.6449.1.2.2.26": nil, "1.3.6.1.4.1.6449.1.2.2.27": nil, "1.3.6.1.4.1.6449.1.2.2.28": nil, "1.3.6.1.4.1.6449.1.2.2.29": nil, "1.3.6.1.4.1.6449.1.2.2.31": nil, "1.3.6.1.4.1.6449.1.2.2.35": nil, "1.3.6.1.4.1.6449.1.2.2.37": nil, "1.3.6.1.4.1.6449.1.2.2.38": nil, "1.3.6.1.4.1.6449.1.2.2.39": nil, "1.3.6.1.4.1.6449.1.2.2.40": nil, "1.3.6.1.4.1.6449.1.2.2.41": nil, "1.3.6.1.4.1.6449.1.2.2.42": nil, "1.3.6.1.4.1.6449.1.2.2.44": nil, "1.3.6.1.4.1.6449.1.2.2.45": nil, "1.3.6.1.4.1.6449.1.2.2.47": nil, "1.3.6.1.4.1.6449.1.2.2.49": nil, "1.3.6.1.4.1.6449.1.2.2.50": nil, "1.3.6.1.4.1.6449.1.2.2.51": nil, "1.3.6.1.4.1.6449.1.2.2.52": nil, "1.3.6.1.4.1.6449.1.2.2.53": nil, "1.3.6.1.4.1.6449.1.2.2.54": nil, "1.3.6.1.4.1.6449.1.2.2.7": nil, "1.3.6.1.4.1.6449.1.2.2.8": nil, "2.16.840.1.114412.1.2": nil, "2.16.840.1.114413.1.7.23.1": nil, "2.16.840.1.114414.1.7.23.1": nil, "2.23.140.1.2.1": nil, }
DomainValidationOIDs contain OIDs that identify DV certs.
var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
ErrUnsupportedAlgorithm results from attempting to perform an operation that involves algorithms that are not currently implemented.
var ExtendedValidationOIDs = map[string]interface{}{ "2.23.140.1.1": nil, "2.23.140.1.3": nil, "2.23.140.1.31": nil, "1.3.6.1.4.1.17326.10.14.2.1.2": nil, "1.3.6.1.4.1.17326.10.14.2.2.2": nil, "1.3.6.1.4.1.17326.10.8.12.1.2": nil, "1.3.6.1.4.1.17326.10.8.12.2.2": nil, "1.3.159.1.17.1": nil, "1.3.6.1.4.1.34697.2.1": nil, "1.3.6.1.4.1.34697.2.2": nil, "1.3.6.1.4.1.34697.2.3": nil, "1.3.6.1.4.1.34697.2.4": nil, "1.3.6.1.4.1.13177.10.1.3.10": nil, "2.16.578.1.26.1.3.3": nil, "1.3.6.1.4.1.36305.2": nil, "1.3.6.1.4.1.22234.2.5.2.3.1": nil, "1.2.616.1.113527.2.5.1.1": nil, "1.3.6.1.4.1.29836.1.10": nil, "1.3.6.1.4.1.6449.1.2.1.5.1": nil, "1.3.6.1.4.1.6334.1.100.1": nil, "2.16.840.1.114412.2.1": nil, "1.3.6.1.4.1.4788.2.202.1": nil, "2.16.840.1.114028.10.1.2": nil, "2.16.792.3.0.4.1.1.4": nil, "1.3.6.1.4.1.14370.1.6": nil, "1.3.6.1.4.1.4146.1.1": nil, "2.16.840.1.114413.1.7.23.3": nil, "1.3.6.1.4.1.14777.6.1.1": nil, "1.3.6.1.4.1.14777.6.1.2": nil, "1.3.6.1.4.1.782.1.2.1.8.1": nil, "1.3.6.1.4.1.8024.0.2.100.1.2": nil, "2.16.840.1.114404.1.1.2.4.1": nil, "1.2.392.200091.100.721.1": nil, "2.16.528.1.1003.1.2.7": nil, "1.3.6.1.4.1.23223.1.1.1": nil, "2.16.840.1.114414.1.7.23.3": nil, "2.16.840.1.114414.1.7.24.3": nil, "2.16.756.1.89.1.2.1.1": nil, "2.16.756.1.83.21.0": nil, "2.16.840.1.113733.1.7.48.1": nil, "1.3.6.1.4.1.40869.1.1.22.3": nil, "1.3.6.1.4.1.7879.13.24.1": nil, "2.16.840.1.113733.1.7.23.6": nil, "2.16.840.1.114171.500.9": nil, "2.16.156.112554.3": nil, "2.16.756.5.14.7.4.8": nil, "2.16.792.3.0.3.1.1.5": nil, }
ExtendedValidationOIDs contains the UNION of Chromium (https://chromium.googlesource.com/chromium/src/net/+/master/cert/ev_root_ca_metadata.cc) and Firefox (http://hg.mozilla.org/mozilla-central/file/tip/security/certverifier/ExtendedValidation.cpp) EV OID lists
var IncorrectPasswordError = errors.New("x509: decryption password incorrect")
IncorrectPasswordError is returned when an incorrect password is detected.
var OrganizationValidationOIDs = map[string]interface{}{ "2.23.140.1.2.2": nil, "2.23.140.1.2.3": nil, "2.16.840.1.114412.1.1": nil, "1.3.6.1.4.1.4788.2.200.1": nil, "2.16.840.1.114413.1.7.23.2": nil, "2.16.528.1.1003.1.2.5.6": nil, "1.3.6.1.4.1.8024.0.2.100.1.1": nil, "2.16.840.1.114414.1.7.23.2": nil, "2.16.792.3.0.3.1.1.2": nil, }
OrganizationValidationOIDs contains CA specific OV OIDs from https://cabforum.org/object-registry/
Functions ¶
func CreateCertificate ¶
func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)
CreateCertificate creates a new X.509 v3 certificate based on a template. The following members of template are currently used:
- AuthorityKeyId
- BasicConstraintsValid
- CRLDistributionPoints
- DNSNames
- EmailAddresses
- ExcludedDNSDomains
- ExcludedEmailAddresses
- ExcludedIPRanges
- ExcludedURIDomains
- ExtKeyUsage
- ExtraExtensions
- IPAddresses
- IsCA
- IssuingCertificateURL
- KeyUsage
- MaxPathLen
- MaxPathLenZero
- NotAfter
- NotBefore
- OCSPServer
- PermittedDNSDomains
- PermittedDNSDomainsCritical
- PermittedEmailAddresses
- PermittedIPRanges
- PermittedURIDomains
- PolicyIdentifiers (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 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.
The PolicyIdentifier and Policies fields are both used to marshal certificate policy OIDs. By default, only the PolicyIdentifier is marshaled, but if the GODEBUG setting "x509usepolicies" has the value "1", the Policies field will be marshaled instead of the PolicyIdentifier field. The Policies field can be used to marshal policy OIDs which have components that are larger than 31 bits.
func CreateCertificateRequest ¶
func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)
CreateCertificateRequest creates a new certificate request based on a template. The following members of template are used:
- SignatureAlgorithm
- Subject
- DNSNames
- EmailAddresses
- IPAddresses
- URIs
- ExtraExtensions
- Attributes (deprecated)
priv is the private key to sign the CSR with, and the corresponding public key will be included in the CSR. It must implement crypto.Signer and its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or ed25519.PrivateKey satisfies this.)
The returned slice is the certificate request in DER encoding.
func CreateRevocationList ¶
func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)
CreateRevocationList creates a new X.509 v2 Certificate Revocation List, according to RFC 5280, based on template.
The CRL is signed by priv which should be the private key associated with the public key in the issuer certificate.
The issuer may not be nil, and the crlSign bit must be set in KeyUsage in order to use it as a CRL issuer.
The issuer distinguished name CRL field and authority key identifier extension are populated using the issuer certificate. issuer must have SubjectKeyId set.
func DecryptPEMBlock
deprecated
DecryptPEMBlock takes a PEM block encrypted according to RFC 1423 and the password used to encrypt it and returns a slice of decrypted DER encoded bytes. It inspects the DEK-Info header to determine the algorithm used for decryption. If no DEK-Info header is present, an error is returned. If an incorrect password is detected an IncorrectPasswordError is returned. Because of deficiencies in the format, it's not always possible to detect an incorrect password. In these cases no error will be returned but the decrypted DER bytes will be random noise.
Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.
func EncryptPEMBlock
deprecated
func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
EncryptPEMBlock returns a PEM block of the specified type holding the given DER encoded data encrypted with the specified algorithm and password according to RFC 1423.
Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.
func FilterByDate ¶
func FilterByDate(chains [][]*Certificate, now time.Time) (current, expired, never [][]*Certificate)
check expirations divides chains into a set of disjoint chains, containing current chains valid now, expired chains that were valid at some point, and the set of chains that were never valid.
func GetRSAPublicKeyJSON ¶
func GetRSAPublicKeyJSON(key *rsa.PublicKey) *jsonKeys.RSAPublicKey
GetRSAPublicKeyJSON - get the jsonKeys.RSAPublicKey for the given standard RSA PublicKey.
func IsEncryptedPEMBlock
deprecated
IsEncryptedPEMBlock returns whether the PEM block is password encrypted according to RFC 1423.
Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.
func MarshalECPrivateKey ¶
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 ¶
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 ¶
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 ¶
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".
func MarshalPKIXPublicKey ¶
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".
func ParseCRL
deprecated
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.
Deprecated: Use ParseRevocationList instead.
func ParseDERCRL
deprecated
func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)
ParseDERCRL parses a DER encoded CRL from the given bytes.
Deprecated: Use ParseRevocationList instead.
func ParseECPrivateKey ¶
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 ¶
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 ¶
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 ¶
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".
func ParsePKIXPublicKey ¶
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".
Example ¶
package main import ( "encoding/pem" "fmt" "github.com/runZeroInc/excrypto/crypto/dsa" "github.com/runZeroInc/excrypto/crypto/ecdsa" "github.com/runZeroInc/excrypto/crypto/ed25519" "github.com/runZeroInc/excrypto/crypto/rsa" "github.com/runZeroInc/excrypto/crypto/x509" ) 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") } }
Output:
func SetFallbackRoots ¶
func SetFallbackRoots(roots *CertPool)
SetFallbackRoots sets the roots to use during certificate verification, if no custom roots are specified and a platform verifier or a system certificate pool is not available (for instance in a container which does not have a root certificate bundle). SetFallbackRoots will panic if roots is nil.
SetFallbackRoots may only be called once, if called multiple times it will panic.
The fallback behavior can be forced on all platforms, even when there is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1 (note that on Windows and macOS this will disable usage of the platform verification APIs and cause the pure Go verifier to be used). Setting x509usefallbackroots=1 without calling SetFallbackRoots has no effect.
Types ¶
type AuthorityInfoAccess ¶
type AuthorityInfoAccess struct { OCSPServer []string `json:"ocsp_urls,omitempty"` IssuingCertificateURL []string `json:"issuer_urls,omitempty"` }
TODO pull out other types
type BasicConstraints ¶
type CABFOrganizationIDASN ¶
type CABFOrganizationIDASN struct { RegistrationSchemeIdentifier string `asn1:"printable"` RegistrationCountry string `asn1:"printable"` RegistrationStateOrProvince string `asn1:"printable,optional,tag:0"` RegistrationReference string `asn1:"utf8"` }
id-CABFOrganizationIdentifier OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) international-organizations(23) ca-browser-forum(140) certificate-extensions(3) cabf-organization-identifier(1) } ext-CABFOrganizationIdentifier EXTENSION ::= { SYNTAX CABFOrganizationIdentifier IDENTIFIED BY id-CABFOrganizationIdentifier } CABFOrganizationIdentifier ::= SEQUENCE { registrationSchemeIdentifier PrintableString (SIZE(3)), registrationCountry PrintableString (SIZE(2)), registrationStateOrProvince [0] IMPLICIT PrintableString OPTIONAL (SIZE(0..128)), registrationReference UTF8String }
type CRLDistributionPoints ¶
type CRLDistributionPoints []string
type CertPool ¶
type CertPool struct {
// contains filtered or unexported fields
}
CertPool is a set of certificates.
func SystemCertPool ¶
SystemCertPool returns a copy of the system cert pool.
On Unix systems other than macOS the environment variables SSL_CERT_FILE and SSL_CERT_DIR can be used to override the system default locations for the SSL certificate file and SSL certificate files directory, respectively. The latter can be a colon-separated list.
Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.
New changes in the system cert pool might not be reflected in subsequent calls.
func (*CertPool) AddCert ¶
func (s *CertPool) AddCert(cert *Certificate)
AddCert adds a certificate to a pool.
func (*CertPool) AddCertWithConstraint ¶
func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)
AddCertWithConstraint adds a certificate to the pool with the additional constraint. When Certificate.Verify builds a chain which is rooted by cert, it will additionally pass the whole chain to constraint to determine its validity. If constraint returns a non-nil error, the chain will be discarded. constraint may be called concurrently from multiple goroutines.
func (*CertPool) AppendCertsFromPEM ¶
AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It appends any certificates found to s and reports whether any certificates were successfully parsed.
On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of root CAs in a format suitable for this function.
func (*CertPool) Certificates ¶
func (s *CertPool) Certificates() []*Certificate
Certificates returns all validate certificates in the pool.
func (*CertPool) Contains ¶
func (s *CertPool) Contains(cert *Certificate) bool
func (*CertPool) Subjects
deprecated
Subjects returns a list of the DER-encoded subjects of all of the certificates in the pool.
Deprecated: if s was returned by SystemCertPool, Subjects will not include the system roots.
type CertValidationLevel ¶
type CertValidationLevel int
The string functions for CertValidationLevel are auto-generated via `go generate <full_path_to_x509_package>` or running `go generate` in the package directory
const ( UnknownValidationLevel CertValidationLevel = 0 DV CertValidationLevel = 1 OV CertValidationLevel = 2 EV CertValidationLevel = 3 )
func (*CertValidationLevel) MarshalJSON ¶
func (c *CertValidationLevel) MarshalJSON() ([]byte, error)
func (CertValidationLevel) String ¶
func (i CertValidationLevel) String() string
type 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 SelfSigned bool SignatureAlgorithmOID asn1.ObjectIdentifier PublicKeyAlgorithm PublicKeyAlgorithm PublicKey any PublicKeyAlgorithmOID asn1.ObjectIdentifier Version int SerialNumber *big.Int Issuer pkix.Name Subject pkix.Name NotBefore, NotAfter time.Time // Validity bounds. ValidityPeriod int KeyUsage KeyUsage IssuerUniqueId asn1.BitString SubjectUniqueId asn1.BitString // 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 // ExtensionsMap contains raw x.509 extensions keyed by OID (in string // representation). It allows fast membership testing of specific OIDs. Like // the Extensions field this field is ignored when marshaling certificates. If // multiple extensions with the same OID are present only the last // pkix.Extension will be in this map. Consult the `Extensions` slice when it // is required to process all extensions including duplicates. ExtensionsMap map[string]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 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 OtherNames []pkix.OtherName DirectoryNames []pkix.Name EDIPartyNames []pkix.EDIPartyName URIs []string RegisteredIDs []asn1.ObjectIdentifier // Issuer Alternative Name values IANOtherNames []pkix.OtherName IANDNSNames []string IANEmailAddresses []string IANDirectoryNames []pkix.Name IANEDIPartyNames []pkix.EDIPartyName IANURIs []string IANIPAddresses []net.IP IANRegisteredIDs []asn1.ObjectIdentifier // Certificate Policies values QualifierId [][]asn1.ObjectIdentifier CPSuri [][]string ExplicitTexts [][]asn1.RawValue NoticeRefOrgnization [][]asn1.RawValue NoticeRefNumbers [][]NoticeNumber ParsedExplicitTexts [][]string ParsedNoticeRefOrganization [][]string UserNotices [][]UserNotice // Name constraints PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. PermittedDNSDomains []string ExcludedDNSDomains []string PermittedEmailAddresses []string ExcludedEmailAddresses []string PermittedURIDomains []string ExcludedURIDomains []string PermittedIPRanges []*net.IPNet ExcludedIPRanges []*net.IPNet PermittedDirectoryNames []pkix.Name ExcludedDirectoryNames []pkix.Name PermittedEdiPartyNames []pkix.EDIPartyName ExcludedEdiPartyNames []pkix.EDIPartyName PermittedRegisteredIDs []asn1.ObjectIdentifier ExcludedRegisteredIDs []asn1.ObjectIdentifier PermittedX400Addresses []string ExcludedX400Addresses []string // FailedToParseNames contains values that are failed to parse, // without returning an error. FailedToParseNames []asn1.RawValue // CRL Distribution Points CRLDistributionPoints []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. PolicyIdentifiers []asn1.ObjectIdentifier ValidationLevel CertValidationLevel // Fingerprints FingerprintMD5 CertificateFingerprint FingerprintSHA1 CertificateFingerprint FingerprintSHA256 CertificateFingerprint FingerprintNoCT CertificateFingerprint // SPKI SPKIFingerprint CertificateFingerprint SPKISubjectFingerprint CertificateFingerprint TBSCertificateFingerprint CertificateFingerprint IsPrecert bool // ValidSignature is true if the certificate was signed by any roots or // intermediates given in a call to (*Certificate).Verify(). ValidSignature bool // CT SignedCertificateTimestampList []*ct.SignedCertificateTimestamp // QWACS CABFOrganizationIdentifier *CABFOrganizationIdentifier QCStatements *QCStatements // CAB Forum Tor Service Descriptor Hash Extensions (see EV Guidelines // Appendix F) TorServiceDescriptors []*TorServiceDescriptorHash // Policies contains all policy identifiers included in the certificate. // In Go 1.22, encoding/gob cannot handle and ignores this field. Policies []OID // PermissiveErrors is a list of errors encountered that were ignored PermissiveErrors []error // contains filtered or unexported fields }
A Certificate represents an X.509 certificate.
func ParseCertificate ¶
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 serial numbers. This behavior can be restored by including "x509negativeserial=1" in the GODEBUG environment variable.
func ParseCertificates ¶
func ParseCertificates(der []byte) ([]*Certificate, error)
ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.
func ParseTBSCertificate ¶
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 (*Certificate) CheckCRLSignature
deprecated
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
CheckCRLSignature checks that the signature in crl is from c.
Deprecated: Use RevocationList.CheckSignatureFrom instead.
func (*Certificate) CheckSignature ¶
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
CheckSignature verifies that signature is a valid signature over signed from c's public key.
This is a low-level API that performs no validity checks on the certificate.
All supported algorithms are accepted, including insecure options like MD5/SHA1
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 full path verifier. Most users should use Certificate.Verify instead.
func (*Certificate) CollectAllNames ¶
func (c *Certificate) CollectAllNames() []string
CollectAllNames - Collect and validate all DNS / URI / IP Address names for a given certificate
func (*Certificate) CreateCRL
deprecated
func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
CreateCRL returns a DER encoded CRL, signed by this Certificate, that contains the given list of revoked certificates.
Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL. To generate a standards compliant CRL, use CreateRevocationList instead.
func (*Certificate) Equal ¶
func (c *Certificate) Equal(other *Certificate) bool
func (*Certificate) GetParsedDNSNames ¶
func (c *Certificate) GetParsedDNSNames(invalidateCache bool) []ParsedDomainName
GetParsedDNSNames returns a list of parsed SAN DNS names. It is used to cache the parsing result and speed up zlint linters. If invalidateCache is true, then the cache is repopulated with current list of string from Certificate.DNSNames. This parameter should always be false, unless the Certificate.DNSNames have been modified after calling GetParsedDNSNames the previous time.
func (*Certificate) GetParsedSubjectCommonName ¶
func (c *Certificate) GetParsedSubjectCommonName(invalidateCache bool) ParsedDomainName
GetParsedCommonName returns parsed subject CommonName. It is used to cache the parsing result and speed up zlint linters. If invalidateCache is true, then the cache is repopulated with current subject CommonName. This parameter should always be false, unless the Certificate.Subject.CommonName have been modified after calling GetParsedSubjectCommonName the previous time.
func (*Certificate) JsonifyExtensions ¶
func (c *Certificate) JsonifyExtensions() (*CertificateExtensions, UnknownCertificateExtensions)
func (*Certificate) MarshalJSON ¶
func (c *Certificate) MarshalJSON() ([]byte, error)
func (*Certificate) PublicKeyAlgorithmName ¶
func (c *Certificate) PublicKeyAlgorithmName() string
func (*Certificate) SignatureAlgorithmName ¶
func (c *Certificate) SignatureAlgorithmName() string
func (*Certificate) SubjectAndKey ¶
func (c *Certificate) SubjectAndKey() *SubjectAndKey
SubjectAndKey returns a SubjectAndKey for this certificate.
func (*Certificate) UnmarshalJSON ¶
func (c *Certificate) UnmarshalJSON(b []byte) error
UnmarshalJSON - intentionally implimented to always error, as this method should not be used. The MarshalJSON method on Certificate condenses data in a way that is not recoverable. Use the x509.ParseCertificate function instead or JSONCertificateWithRaw Marshal method
func (*Certificate) ValidateWithStupidDetail
deprecated
func (c *Certificate) ValidateWithStupidDetail(opts VerifyOptions) (chains []CertificateChain, validation *Validation, err error)
ValidateWithStupidDetail fills out a Validation struct given a leaf certificate and intermediates / roots. If opts.DNSName is set, then it will also check if the domain matches.
Deprecated: Use verifier.Verify() instead.
func (*Certificate) Verify ¶
func (c *Certificate) Verify(opts VerifyOptions) (current, expired, never [][]*Certificate, err error)
Verify attempts to verify c by building one or more chains from c to a certificate in opts.Roots, using certificates in opts.Intermediates if needed. If successful, it returns one or more chains where the first element of the chain is c and the last element is from opts.Roots.
If opts.Roots is nil, the platform verifier might be used, and verification details might differ from what is described below. If system roots are unavailable the returned error will be of type SystemRootsError.
Name constraints in the intermediates will be applied to all names claimed in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim example.com if an intermediate doesn't permit it, even if example.com is not the name being validated. Note that DirectoryName constraints are not supported.
Name constraint validation follows the rules from RFC 5280, with the addition that DNS name constraints may use the leading period format defined for emails and URIs. When a constraint has a leading period it indicates that at least one additional label must be prepended to the constrained name to be considered valid.
Extended Key Usage values are enforced nested down a chain, so an intermediate or root that enumerates EKUs prevents a leaf from asserting an EKU not in that list. (While this is not specified, it is common practice in order to limit the types of certificates a CA can issue.)
Certificates 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 main import ( "encoding/pem" "github.com/runZeroInc/excrypto/crypto/x509" ) 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()) } }
Output:
func (*Certificate) VerifyHostname ¶
func (c *Certificate) VerifyHostname(h string) error
VerifyHostname returns nil if c is a valid certificate for the named host. Otherwise it returns an error describing the mismatch.
IP addresses can be optionally enclosed in square brackets and are checked against the IPAddresses field. Other names are checked case insensitively against the DNSNames field. If the names are valid hostnames, the certificate fields can have a wildcard as the complete left-most label (e.g. *.example.com).
Note that the legacy Common Name field is ignored.
type CertificateChain ¶
type CertificateChain []*Certificate
CertificateChain is a slice of certificates. The 0'th element is the leaf, and the last element is a root. Successive elements have a child-parent relationship.
func (CertificateChain) AppendToFreshChain ¶
func (chain CertificateChain) AppendToFreshChain(c *Certificate) CertificateChain
func (CertificateChain) CertificateInChain ¶
func (chain CertificateChain) CertificateInChain(c *Certificate) bool
CertificateInChain returns true if c is in the chain.
func (CertificateChain) CertificateSubjectAndKeyInChain ¶
func (chain CertificateChain) CertificateSubjectAndKeyInChain(c *Certificate) bool
CertificateSubjectAndKeyInChain returns true if the SubjectAndKey from c is found in any certificate in the chain.
func (CertificateChain) Range ¶
func (chain CertificateChain) Range(f func(int, *Certificate))
Range runs a function on each element of chain. It can modify each certificate in place.
func (CertificateChain) SubjectAndKeyInChain ¶
func (chain CertificateChain) SubjectAndKeyInChain(sk *SubjectAndKey) bool
SubjectAndKeyInChain returns true if the given SubjectAndKey is found in any certificate in the chain.
type CertificateExtensions ¶
type CertificateExtensions struct { KeyUsage KeyUsage `json:"key_usage,omitempty"` BasicConstraints *BasicConstraints `json:"basic_constraints,omitempty"` SubjectAltName *GeneralNames `json:"subject_alt_name,omitempty"` IssuerAltName *GeneralNames `json:"issuer_alt_name,omitempty"` NameConstraints *NameConstraints `json:"name_constraints,omitempty"` CRLDistributionPoints CRLDistributionPoints `json:"crl_distribution_points,omitempty"` AuthKeyID SubjAuthKeyId `json:"authority_key_id,omitempty"` SubjectKeyID SubjAuthKeyId `json:"subject_key_id,omitempty"` ExtendedKeyUsage *ExtendedKeyUsageExtension `json:"extended_key_usage,omitempty"` CertificatePolicies *CertificatePoliciesData `json:"certificate_policies,omitempty"` AuthorityInfoAccess *AuthorityInfoAccess `json:"authority_info_access,omitempty"` IsPrecert IsPrecert `json:"ct_poison,omitempty"` SignedCertificateTimestampList []*ct.SignedCertificateTimestamp `json:"signed_certificate_timestamps,omitempty"` TorServiceDescriptors []*TorServiceDescriptorHash `json:"tor_service_descriptors,omitempty"` CABFOrganizationIdentifier *CABFOrganizationIdentifier `json:"cabf_organization_id,omitempty"` QCStatements *QCStatements `json:"qc_statements,omitempty"` }
type CertificateFingerprint ¶
type CertificateFingerprint []byte
CertificateFingerprint represents a digest/fingerprint of some data. It can easily be encoded to hex and JSON (as a hex string).
func MD5Fingerprint ¶
func MD5Fingerprint(data []byte) CertificateFingerprint
MD5Fingerprint creates a fingerprint of data using the MD5 hash algorithm.
func SHA1Fingerprint ¶
func SHA1Fingerprint(data []byte) CertificateFingerprint
SHA1Fingerprint creates a fingerprint of data using the SHA1 hash algorithm.
func SHA256Fingerprint ¶
func SHA256Fingerprint(data []byte) CertificateFingerprint
SHA256Fingerprint creates a fingerprint of data using the SHA256 hash algorithm.
func SHA512Fingerprint ¶
func SHA512Fingerprint(data []byte) CertificateFingerprint
SHA512Fingerprint creates a fingerprint of data using the SHA256 hash algorithm.
func (CertificateFingerprint) Equal ¶
func (f CertificateFingerprint) Equal(other CertificateFingerprint) bool
Equal returns true if the fingerprints are bytewise-equal.
func (CertificateFingerprint) Hex ¶
func (f CertificateFingerprint) Hex() string
Hex returns the given fingerprint encoded as a hex string.
func (*CertificateFingerprint) MarshalJSON ¶
func (f *CertificateFingerprint) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface, and marshals the fingerprint as a hex string.
type CertificateInvalidError ¶
type CertificateInvalidError struct { Cert *Certificate Reason InvalidReason Detail string }
CertificateInvalidError results when an odd error occurs. Users of this library probably want to handle all these errors uniformly.
func (CertificateInvalidError) Error ¶
func (e CertificateInvalidError) Error() string
type CertificatePolicies ¶
type CertificatePolicies []CertificatePoliciesJSON
type CertificatePoliciesData ¶
type CertificatePoliciesData struct { PolicyIdentifiers []asn1.ObjectIdentifier QualifierId [][]asn1.ObjectIdentifier CPSUri [][]string ExplicitTexts [][]string NoticeRefOrganization [][]string NoticeRefNumbers [][]NoticeNumber UserNotices [][]UserNotice }
func (*CertificatePoliciesData) MarshalJSON ¶
func (cp *CertificatePoliciesData) MarshalJSON() ([]byte, error)
type CertificatePoliciesJSON ¶
type CertificatePoliciesJSON struct { PolicyIdentifier string `json:"id,omitempty"` CPSUri []string `json:"cps,omitempty"` UserNotice []UserNoticeData `json:"user_notice,omitempty"` }
type CertificateRequest ¶
type CertificateRequest struct { Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. RawSubject []byte // DER encoded Subject. Version int Signature []byte SignatureAlgorithm SignatureAlgorithm PublicKeyAlgorithm PublicKeyAlgorithm PublicKey any 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 []string }
CertificateRequest represents a PKCS #10, certificate signature request.
func ParseCertificateRequest ¶
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
ParseCertificateRequest parses a single certificate request from the given ASN.1 DER data.
func (*CertificateRequest) CheckSignature ¶
func (c *CertificateRequest) CheckSignature() error
CheckSignature reports whether the signature on c is valid.
type CertificateType ¶
type CertificateType int
CertificateType represents whether a certificate is a root, intermediate, or leaf.
const ( CertificateTypeUnknown CertificateType = 0 CertificateTypeLeaf CertificateType = 1 CertificateTypeIntermediate CertificateType = 2 CertificateTypeRoot CertificateType = 3 )
CertificateType constants. Values should not be considered significant aside from CertificateTypeUnknown is the zero value.
func (CertificateType) MarshalJSON ¶
func (t CertificateType) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface. Any unknown integer value is considered the same as CertificateTypeUnknown.
func (*CertificateType) UnmarshalJSON ¶
func (t *CertificateType) UnmarshalJSON(b []byte) error
UnmarshalJSON implements the json.Unmarshaler interface. Any unknown string is considered the same CertificateTypeUnknown.
type ConstraintViolationError ¶
type ConstraintViolationError struct{}
ConstraintViolationError results when a requested usage is not permitted by a certificate. For example: checking a signature when the public key isn't a certificate signing key.
func (ConstraintViolationError) Error ¶
func (ConstraintViolationError) Error() string
type DSAPublicKeyJSON ¶
type DSAPublicKeyJSON struct { G []byte `json:"g"` P []byte `json:"p"` Q []byte `json:"q"` Y []byte `json:"y"` }
DSAPublicKeyJSON - used to condense several fields from a DSA public key into one field for use in JSONCertificate. Uses default JSON marshal and unmarshal methods
func GetDSAPublicKeyJSON ¶
func GetDSAPublicKeyJSON(key *dsa.PublicKey) *DSAPublicKeyJSON
GetDSAPublicKeyJSON - get the DSAPublicKeyJSON for the given standard DSA PublicKey.
type ECDSAPublicKeyJSON ¶
type ECDSAPublicKeyJSON struct { B []byte `json:"b"` Curve string `json:"curve"` Gx []byte `json:"gx"` Gy []byte `json:"gy"` Length int `json:"length"` N []byte `json:"n"` P []byte `json:"p"` Pub []byte `json:"pub,omitempty"` X []byte `json:"x"` Y []byte `json:"y"` }
ECDSAPublicKeyJSON - used to condense several fields from a ECDSA public key into one field for use in JSONCertificate. Uses default JSON marshal and unmarshal methods
func GetECDSAPublicKeyJSON ¶
func GetECDSAPublicKeyJSON(key *ecdsa.PublicKey) *ECDSAPublicKeyJSON
GetECDSAPublicKeyJSON - get the GetECDSAPublicKeyJSON for the given standard ECDSA PublicKey.
type ExtKeyUsage ¶
type ExtKeyUsage int
ExtKeyUsage represents an extended set of actions that are valid for a given key. Each of the ExtKeyUsage* constants define a unique action.
const ( ExtKeyUsageAppleCodeSigning ExtKeyUsage = iota ExtKeyUsageAppleCodeSigningDevelopment ExtKeyUsageAppleSoftwareUpdateSigning ExtKeyUsageAppleCodeSigningThirdParty ExtKeyUsageAppleResourceSigning ExtKeyUsageAppleIchatSigning ExtKeyUsageAppleIchatEncryption ExtKeyUsageAppleSystemIdentity ExtKeyUsageAppleCryptoEnv ExtKeyUsageAppleCryptoProductionEnv ExtKeyUsageAppleCryptoMaintenanceEnv ExtKeyUsageAppleCryptoTestEnv ExtKeyUsageAppleCryptoDevelopmentEnv ExtKeyUsageAppleCryptoQos ExtKeyUsageAppleCryptoTier0Qos ExtKeyUsageAppleCryptoTier1Qos ExtKeyUsageAppleCryptoTier2Qos ExtKeyUsageAppleCryptoTier3Qos ExtKeyUsageMicrosoftCertTrustListSigning ExtKeyUsageMicrosoftQualifiedSubordinate ExtKeyUsageMicrosoftKeyRecovery3 ExtKeyUsageMicrosoftDocumentSigning ExtKeyUsageMicrosoftLifetimeSigning ExtKeyUsageMicrosoftMobileDeviceSoftware ExtKeyUsageMicrosoftSmartDisplay ExtKeyUsageMicrosoftCspSignature ExtKeyUsageMicrosoftTimestampSigning ExtKeyUsageMicrosoftServerGatedCrypto ExtKeyUsageMicrosoftSgcSerialized ExtKeyUsageMicrosoftEncryptedFileSystem ExtKeyUsageMicrosoftEfsRecovery ExtKeyUsageMicrosoftWhqlCrypto ExtKeyUsageMicrosoftNt5Crypto ExtKeyUsageMicrosoftOemWhqlCrypto ExtKeyUsageMicrosoftEmbeddedNtCrypto ExtKeyUsageMicrosoftRootListSigner ExtKeyUsageMicrosoftDrm ExtKeyUsageMicrosoftDrmIndividualization ExtKeyUsageMicrosoftLicenses ExtKeyUsageMicrosoftLicenseServer ExtKeyUsageMicrosoftEnrollmentAgent ExtKeyUsageMicrosoftSmartcardLogon ExtKeyUsageMicrosoftCaExchange ExtKeyUsageMicrosoftKeyRecovery21 ExtKeyUsageMicrosoftSystemHealth ExtKeyUsageMicrosoftSystemHealthLoophole ExtKeyUsageMicrosoftKernelModeCodeSigning ExtKeyUsageServerAuth ExtKeyUsageDvcs ExtKeyUsageSbgpCertAaServiceAuth ExtKeyUsageEapOverPpp ExtKeyUsageEapOverLan ExtKeyUsageClientAuth ExtKeyUsageCodeSigning ExtKeyUsageEmailProtection ExtKeyUsageIpsecEndSystem ExtKeyUsageIpsecTunnel ExtKeyUsageIpsecUser ExtKeyUsageTimeStamping ExtKeyUsageOcspSigning ExtKeyUsageIpsecIntermediateSystemUsage ExtKeyUsageNetscapeServerGatedCrypto ExtKeyUsageAny ExtKeyUsageIPSECEndSystem ExtKeyUsageIPSECTunnel ExtKeyUsageIPSECUser ExtKeyUsageOCSPSigning ExtKeyUsageMicrosoftCommercialCodeSigning ExtKeyUsageMicrosoftKernelCodeSigning )
type ExtendedKeyUsage ¶
type ExtendedKeyUsage []ExtKeyUsage
type ExtendedKeyUsageExtension ¶
type ExtendedKeyUsageExtension struct { Known ExtendedKeyUsage Unknown []asn1.ObjectIdentifier }
func (*ExtendedKeyUsageExtension) MarshalJSON ¶
func (e *ExtendedKeyUsageExtension) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshal interface. The output is a struct of bools, with an additional `Value` field containing the actual OIDs.
func (*ExtendedKeyUsageExtension) UnmarshalJSON ¶
func (e *ExtendedKeyUsageExtension) UnmarshalJSON(b []byte) error
type GeneralNames ¶
type GeneralNames struct { DirectoryNames []pkix.Name DNSNames []string EDIPartyNames []pkix.EDIPartyName EmailAddresses []string IPAddresses []net.IP OtherNames []pkix.OtherName RegisteredIDs []asn1.ObjectIdentifier URIs []string }
GeneralNames corresponds an X.509 GeneralName defined in Section 4.2.1.6 of RFC 5280.
GeneralName ::= CHOICE { otherName [0] AnotherName, rfc822Name [1] IA5String, dNSName [2] IA5String, x400Address [3] ORAddress, directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6] IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER }
func (*GeneralNames) MarshalJSON ¶
func (gn *GeneralNames) MarshalJSON() ([]byte, error)
func (*GeneralNames) UnmarshalJSON ¶
func (gn *GeneralNames) UnmarshalJSON(b []byte) error
type HostnameError ¶
type HostnameError struct { Certificate *Certificate Host string }
HostnameError results when the set of authorized names doesn't match the requested name.
func (HostnameError) Error ¶
func (h HostnameError) Error() string
type InsecureAlgorithmError ¶
type InsecureAlgorithmError SignatureAlgorithm
An InsecureAlgorithmError 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.
func (InsecureAlgorithmError) Error ¶
func (e InsecureAlgorithmError) Error() string
type InvalidReason ¶
type InvalidReason int
const ( // NotAuthorizedToSign results when a certificate is signed by another // which isn't marked as a CA certificate. NotAuthorizedToSign InvalidReason = iota // Expired results when a certificate has expired, based on the time // given in the VerifyOptions. Expired // CANotAuthorizedForThisName results when an intermediate or root // certificate has a name constraint which doesn't permit a DNS or // other name (including IP address) in the leaf certificate. CANotAuthorizedForThisName // CANotAuthorizedForThisEmail results when an intermediate or root // certificate has a name constraint which doesn't include the email // being checked. CANotAuthorizedForThisEmail // CANotAuthorizedForThisIP results when an intermediate or root // certificate has a name constraint which doesn't include the IP // being checked. CANotAuthorizedForThisIP // CANotAuthorizedForThisDirectory results when an intermediate or root // certificate has a name constraint which doesn't include the directory // being checked. CANotAuthorizedForThisDirectory // 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 // NeverValid results when the certificate could never have been valid due to // some date-related issue, e.g. NotBefore > NotAfter. NeverValid // IsSelfSigned results when the certificate is self-signed and not a trusted // root. IsSelfSigned // NameConstraintsWithoutSANs is a legacy error and is no longer returned. NameConstraintsWithoutSANs // UnconstrainedName results when a CA certificate contains permitted // name constraints, but leaf certificate contains a name of an // unsupported or unconstrained type. UnconstrainedName // TooManyConstraints results when the number of comparison operations // needed to check a certificate exceeds the limit set by // VerifyOptions.MaxConstraintComparisions. This limit exists to // prevent pathological certificates can consuming excessive amounts of // CPU time to verify. TooManyConstraints // CANotAuthorizedForExtKeyUsage results when an intermediate or root // certificate does not permit a requested extended key usage. CANotAuthorizedForExtKeyUsage )
type JSONCertificate ¶
type JSONCertificate struct { Version int `json:"version"` SerialNumber string `json:"serial_number"` SignatureAlgorithm JSONSignatureAlgorithm `json:"signature_algorithm"` Issuer pkix.Name `json:"issuer"` IssuerDN string `json:"issuer_dn,omitempty"` Validity JSONValidity `json:"validity"` Subject pkix.Name `json:"subject"` SubjectDN string `json:"subject_dn,omitempty"` SubjectKeyInfo JSONSubjectKeyInfo `json:"subject_key_info"` Extensions *CertificateExtensions `json:"extensions,omitempty"` UnknownExtensions UnknownCertificateExtensions `json:"unknown_extensions,omitempty"` Signature JSONSignature `json:"signature"` FingerprintMD5 CertificateFingerprint `json:"fingerprint_md5"` FingerprintSHA1 CertificateFingerprint `json:"fingerprint_sha1"` FingerprintSHA256 CertificateFingerprint `json:"fingerprint_sha256"` FingerprintNoCT CertificateFingerprint `json:"tbs_noct_fingerprint"` SPKISubjectFingerprint CertificateFingerprint `json:"spki_subject_fingerprint"` TBSCertificateFingerprint CertificateFingerprint `json:"tbs_fingerprint"` ValidationLevel CertValidationLevel `json:"validation_level"` Names []string `json:"names,omitempty"` Redacted bool `json:"redacted"` }
JSONCertificate - used to condense data from x509.Certificate when marhsaling into JSON. This struct has a distinct and independent layout from x509.Certificate, mostly for condensing data across repetitive fields and making it more presentable.
func (*JSONCertificate) UnmarshalJSON ¶
func (jc *JSONCertificate) UnmarshalJSON(b []byte) error
UnmarshalJSON - intentionally implimented to always error, as this method should not be used. The MarshalJSON method on Certificate condenses data in a way that is not recoverable. Use the x509.ParseCertificate function instead or JSONCertificateWithRaw Marshal method
type JSONCertificateWithRaw ¶
type JSONCertificateWithRaw struct {
Raw []byte `json:"raw,omitempty"`
}
JSONCertificateWithRaw - intermediate struct for unmarshaling json of a certificate - the raw is require since the MarshalJSON method on Certificate condenses data in a way that makes extraction to the original in Unmarshal impossible. The JSON output of Marshal is not even used to construct a certificate, all we need is raw
func (*JSONCertificateWithRaw) ParseRaw ¶
func (c *JSONCertificateWithRaw) ParseRaw() (*Certificate, error)
ParseRaw - for converting the intermediate object JSONCertificateWithRaw into a parsed Certificate see description of JSONCertificateWithRaw for why this is used instead of UnmarshalJSON methods
type JSONSignature ¶
type JSONSignature struct { SignatureAlgorithm JSONSignatureAlgorithm `json:"signature_algorithm"` Value []byte `json:"value"` Valid bool `json:"valid"` SelfSigned bool `json:"self_signed"` }
JSONSignature - used to condense several fields from x509.Certificate related to the signature into one field within JSONCertificate Unfortunately, this struct cannot have its own Marshal method since it needs information from multiple fields in x509.Certificate
type JSONSignatureAlgorithm ¶
type JSONSignatureAlgorithm struct { Name string `json:"name,omitempty"` OID pkix.AuxOID `json:"oid"` }
JSONSignatureAlgorithm is the intermediate type used when marshaling a PublicKeyAlgorithm out to JSON.
type JSONSubjectKeyInfo ¶
type JSONSubjectKeyInfo struct { KeyAlgorithm PublicKeyAlgorithm `json:"key_algorithm"` RSAPublicKey *jsonKeys.RSAPublicKey `json:"rsa_public_key,omitempty"` DSAPublicKey *DSAPublicKeyJSON `json:"dsa_public_key,omitempty"` ECDSAPublicKey *ECDSAPublicKeyJSON `json:"ecdsa_public_key,omitempty"` SPKIFingerprint CertificateFingerprint `json:"fingerprint_sha256"` }
JSONSubjectKeyInfo - used to condense several fields from x509.Certificate related to the subject public key into one field within JSONCertificate Unfortunately, this struct cannot have its own Marshal method since it needs information from multiple fields in x509.Certificate
type JSONValidity ¶
type JSONValidity struct { ValidityPeriod int // contains filtered or unexported fields }
JSONValidity - used to condense several fields related to validity in x509.Certificate into one field within JSONCertificate Unfortunately, this struct cannot have its own Marshal method since it needs information from multiple fields in x509.Certificate
func (*JSONValidity) MarshalJSON ¶
func (*JSONValidity) UnmarshalJSON ¶
type KeyUsage ¶
type KeyUsage int
KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.
func (KeyUsage) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface
func (*KeyUsage) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshler interface
type MonetaryValue ¶
type NameConstraints ¶
type NameConstraints struct { Critical bool `json:"critical"` PermittedDNSDomains []string PermittedEmailAddresses []string PermittedURIDomains []string PermittedIPRanges []*net.IPNet PermittedDirectoryNames []pkix.Name PermittedEdiPartyNames []pkix.EDIPartyName PermittedRegisteredIDs []asn1.ObjectIdentifier ExcludedEmailAddresses []string ExcludedDNSDomains []string ExcludedURIDomains []string ExcludedIPRanges []*net.IPNet ExcludedDirectoryNames []pkix.Name ExcludedEdiPartyNames []pkix.EDIPartyName ExcludedRegisteredIDs []asn1.ObjectIdentifier }
func (NameConstraints) MarshalJSON ¶
func (nc NameConstraints) MarshalJSON() ([]byte, error)
func (*NameConstraints) UnmarshalJSON ¶
func (nc *NameConstraints) UnmarshalJSON(b []byte) error
type NameConstraintsJSON ¶
type NameConstraintsJSON struct { Critical bool `json:"critical"` PermittedDNSDomains []string `json:"permitted_names,omitempty"` PermittedEmailAddresses []string `json:"permitted_email_addresses,omitempty"` PermittedURIDomains []string `json:"permitted_uris,omitempty"` PermittedIPRanges []*net.IPNet `json:"permitted_ip_addresses,omitempty"` PermittedDirectoryNames []pkix.Name `json:"permitted_directory_names,omitempty"` PermittedEdiPartyNames []pkix.EDIPartyName `json:"permitted_edi_party_names,omitempty"` PermittedRegisteredIDs []string `json:"permitted_registred_id,omitempty"` ExcludedDNSDomains []string `json:"excluded_names,omitempty"` ExcludedEmailAddresses []string `json:"excluded_email_addresses,omitempty"` ExcludedURIDomains []string `json:"excluded_uris,omitempty"` ExcludedIPRanges []*net.IPNet `json:"excluded_ip_addresses,omitempty"` ExcludedDirectoryNames []pkix.Name `json:"excluded_directory_names,omitempty"` ExcludedEdiPartyNames []pkix.EDIPartyName `json:"excluded_edi_party_names,omitempty"` ExcludedRegisteredIDs []string `json:"excluded_registred_id,omitempty"` }
type NoticeNumber ¶
type NoticeNumber []int
type NoticeReference ¶
type NoticeReference struct { Organization string `json:"organization,omitempty"` NoticeNumbers NoticeNumber `json:"notice_numbers,omitempty"` }
type OID ¶
type OID struct {
// contains filtered or unexported fields
}
An OID represents an ASN.1 OBJECT IDENTIFIER.
func OIDFromInts ¶
OIDFromInts creates a new OID using ints, each integer is a separate component.
func ParseOID ¶
ParseOID parses a Object Identifier string, represented by ASCII numbers separated by dots.
func (OID) AppendBinary ¶
AppendBinary implements encoding.BinaryAppender
func (OID) AppendText ¶
AppendText implements encoding.TextAppender
func (OID) EqualASN1OID ¶
func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool
EqualASN1OID returns whether an OID equals an asn1.ObjectIdentifier. If asn1.ObjectIdentifier cannot represent the OID specified by oid, because a component of OID requires more than 31 bits, it returns false.
func (OID) MarshalBinary ¶
MarshalBinary implements encoding.BinaryMarshaler
func (OID) MarshalText ¶
MarshalText implements encoding.TextMarshaler
func (*OID) UnmarshalBinary ¶
UnmarshalBinary implements encoding.BinaryUnmarshaler
func (*OID) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler
type PDSLocation ¶
type PDSLocations ¶
type PDSLocations struct {
Locations []PDSLocation `json:"locations,omitempty"`
}
type PEMCipher ¶
type PEMCipher int
const ( PEMCipherDES PEMCipher PEMCipher3DES PEMCipherAES128 PEMCipherAES192 PEMCipherAES256 )
Possible values for the EncryptPEMBlock encryption algorithm.
type ParsedDomainName ¶
type ParsedDomainName struct { DomainString string ParsedDomain *publicsuffix.DomainName ParseError error }
ParsedDomainName is a structure holding a parsed domain name (CommonName or DNS SAN) and a parsing error.
type ParsedQCStatements ¶
type ParsedQCStatements struct { ETSICompliance []bool `json:"etsi_compliance,omitempty"` SSCD []bool `json:"sscd,omitempty"` Types []QCType `json:"types,omitempty"` Limit []MonetaryValue `json:"limit,omitempty"` PDSLocations []PDSLocations `json:"pds_locations,omitempty"` RetentionPeriod []int `json:"retention_period,omitempty"` Legislation []QCLegistation `json:"legislation,omitempty"` }
type PublicKeyAlgorithm ¶
type PublicKeyAlgorithm int
const ( UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota RSA DSA // Only supported for parsing. ECDSA Ed25519 X25519 )
func (*PublicKeyAlgorithm) MarshalJSON ¶
func (p *PublicKeyAlgorithm) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface
func (PublicKeyAlgorithm) String ¶
func (algo PublicKeyAlgorithm) String() string
func (*PublicKeyAlgorithm) UnmarshalJSON ¶
func (p *PublicKeyAlgorithm) UnmarshalJSON(b []byte) error
UnmarshalJSON implements the json.Unmarshaler interface
type QCLegistation ¶
type QCLegistation struct {
CountryCodes []string `json:"country_codes,omitempty"`
}
type QCStatementASN ¶
type QCStatementASN struct { StatementID asn1.ObjectIdentifier StatementInfo asn1.RawValue `asn1:"optional"` }
func (*QCStatementASN) MarshalJSON ¶
func (s *QCStatementASN) MarshalJSON() ([]byte, error)
type QCStatements ¶
type QCStatements struct { StatementIDs []string `json:"ids,omitempty"` ParsedStatements *ParsedQCStatements `json:"parsed,omitempty"` }
func (*QCStatements) Parse ¶
func (q *QCStatements) Parse(in *QCStatementsASN) error
type QCStatementsASN ¶
type QCStatementsASN struct {
QCStatements []QCStatementASN
}
type QCType ¶
type QCType struct {
TypeIdentifiers []asn1.ObjectIdentifier
}
func (*QCType) MarshalJSON ¶
type RevocationList ¶
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. Issuer pkix.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 []byte 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. SignatureAlgorithm SignatureAlgorithm // 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. ThisUpdate time.Time // NextUpdate is used to populate the nextUpdate field in the CRL, which // indicates the date by which the next CRL will be issued. NextUpdate // must be greater than ThisUpdate. NextUpdate time.Time // 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 a Certificate Revocation List (CRL) as specified by RFC 5280.
func ParseRevocationList ¶
func ParseRevocationList(der []byte) (*RevocationList, error)
ParseRevocationList parses a X509 v2 Certificate Revocation List from the given ASN.1 DER data.
func (*RevocationList) CheckSignatureFrom ¶
func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error
CheckSignatureFrom verifies that the signature on rl is a valid signature from issuer.
type RevocationListEntry ¶
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. RevocationTime time.Time // 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). ReasonCode int // 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 revokedCertificates sequence of a CRL.
type SignatureAlgorithm ¶
type SignatureAlgorithm int
const ( UnknownSignatureAlgorithm SignatureAlgorithm = iota MD2WithRSA // Unsupported. MD5WithRSA // Only supported for signing, not verification. SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses. SHA256WithRSA SHA384WithRSA SHA512WithRSA DSAWithSHA1 // Unsupported. DSAWithSHA256 // Unsupported. ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses. ECDSAWithSHA256 ECDSAWithSHA384 ECDSAWithSHA512 SHA256WithRSAPSS SHA384WithRSAPSS SHA512WithRSAPSS PureEd25519 )
func GetSignatureAlgorithmFromAI ¶
func GetSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm
GetSignatureAlgorithmFromAI is an exported wrapper of getSignatureAlgorithmFromAI
func (*SignatureAlgorithm) MarshalJSON ¶
func (s *SignatureAlgorithm) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface MAY NOT PRESERVE ORIGINAL OID FROM CERTIFICATE - CONSIDER USING jsonifySignatureAlgorithm INSTEAD!
func (SignatureAlgorithm) String ¶
func (algo SignatureAlgorithm) String() string
func (*SignatureAlgorithm) UnmarshalJSON ¶
func (s *SignatureAlgorithm) UnmarshalJSON(b []byte) error
UnmarshalJSON implements the json.Unmarshler interface
type SignatureAlgorithmOID ¶
type SignatureAlgorithmOID asn1.ObjectIdentifier
type SubjAuthKeyId ¶
type SubjAuthKeyId []byte
func (SubjAuthKeyId) MarshalJSON ¶
func (kid SubjAuthKeyId) MarshalJSON() ([]byte, error)
type SubjectAndKey ¶
type SubjectAndKey struct { RawSubject []byte RawSubjectPublicKeyInfo []byte Fingerprint CertificateFingerprint PublicKey interface{} PublicKeyAlgorithm PublicKeyAlgorithm }
SubjectAndKey represents a (subjecty, subject public key info) tuple.
type SystemRootsError ¶
type SystemRootsError struct {
Err error
}
SystemRootsError results when we fail to load the system root certificates.
func (SystemRootsError) Error ¶
func (se SystemRootsError) Error() string
func (SystemRootsError) Unwrap ¶
func (se SystemRootsError) Unwrap() error
type TorServiceDescriptorHash ¶
type TorServiceDescriptorHash struct { Onion string `json:"onion"` Algorithm pkix.AlgorithmIdentifier `json:"-"` AlgorithmName string `json:"algorithm_name"` Hash CertificateFingerprint `json:"hash"` HashBits int `json:"hash_bits"` }
TorServiceDescriptorHash is a structure corrsponding to the TorServiceDescriptorHash SEQUENCE described in Appendix F ("Issuance of Certificates for .onion Domain Names").
Each TorServiceDescriptorHash holds an onion URI (a utf8 string with the .onion address that was validated), a hash algorithm name (computed based on the pkix.AlgorithmIdentifier in the TorServiceDescriptorHash), the hash bytes (computed over the DER encoding of the ASN.1 SubjectPublicKey of the .onion service), and the number of bits in the hash bytes.
type UnhandledCriticalExtension ¶
type UnhandledCriticalExtension struct { ID asn1.ObjectIdentifier Message string }
START CT CHANGES
func (UnhandledCriticalExtension) Error ¶
func (h UnhandledCriticalExtension) Error() string
type UnknownAuthorityError ¶
type UnknownAuthorityError struct { Cert *Certificate // contains filtered or unexported fields }
UnknownAuthorityError results when the certificate issuer is unknown
func (UnknownAuthorityError) Error ¶
func (e UnknownAuthorityError) Error() string
type UserNotice ¶
type UserNotice struct { ExplicitText *string NoticeReference *NoticeReference }
type UserNoticeData ¶
type UserNoticeData struct { ExplicitText string `json:"explicit_text,omitempty"` NoticeReference []NoticeReference `json:"notice_reference,omitempty"` }
type Validation ¶
type Validation struct { BrowserTrusted bool `json:"browser_trusted"` BrowserError string `json:"browser_error,omitempty"` MatchesDomain bool `json:"matches_domain,omitempty"` Domain string `json:"-"` }
Validation stores different validation levels for a given certificate
type VerifyOptions ¶
type VerifyOptions struct { // DNSName, if set, is checked against the leaf certificate with // Certificate.VerifyHostname or the platform verifier. DNSName string EmailAddress string IPAddress net.IP // Intermediates is an optional pool of certificates that are not trust // anchors, but can be used to form a chain from the leaf certificate to a // root certificate. Intermediates *CertPool // Roots is the set of trusted root certificates the leaf certificate needs // to chain up to. If nil, the system roots or the platform verifier are used. Roots *CertPool // CurrentTime is used to check the validity of all certificates in the // chain. If zero, the current time is used. CurrentTime time.Time // KeyUsages specifies which Extended Key Usage values are acceptable. A // chain is accepted if it allows any of the listed values. An empty list // means ExtKeyUsageServerAuth. To accept any key usage, include ExtKeyUsageAny. KeyUsages []ExtKeyUsage // MaxConstraintComparisions is the maximum number of comparisons to // perform when checking a given certificate's name constraints. If // zero, a sensible default is used. This limit prevents pathological // certificates from consuming excessive amounts of CPU time when // validating. It does not apply to the platform verifier. MaxConstraintComparisions int }
VerifyOptions contains parameters for Certificate.Verify.
Source Files
¶
- cert_pool.go
- certificate_type.go
- chain.go
- extended_key_usage.go
- extensions.go
- fallback.go
- fingerprint.go
- generated_certvalidationlevel_string.go
- json.go
- names.go
- notboring.go
- oid.go
- parser.go
- pem_decrypt.go
- pkcs1.go
- pkcs8.go
- qc_statements.go
- root.go
- sec1.go
- tor_service_descriptor.go
- validation.go
- verify.go
- x509.go
Directories
¶
Path | Synopsis |
---|---|
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. |
revocation
|
|
ocsp
Package ocsp parses OCSP responses as specified in RFC 2560.
|
Package ocsp parses OCSP responses as specified in RFC 2560. |
ZIntermediate is a command line utility for verifying a set prospective intermediate certificates against a root store.
|
ZIntermediate is a command line utility for verifying a set prospective intermediate certificates against a root store. |