version: 1.10

package x509

import "crypto/x509"

Overview

Package x509 parses X.509-encoded keys and certificates.

On UNIX systems 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.

Index

Examples

Package files

cert_pool.go pem_decrypt.go pkcs1.go pkcs8.go root.go root_linux.go root_unix.go sec1.go verify.go x509.go

Variables

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

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

IncorrectPasswordError is returned when an incorrect password is detected.

func CreateCertificate

  1. 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: AuthorityKeyId, BasicConstraintsValid,
DNSNames, ExcludedDNSDomains, ExtKeyUsage, IsCA, KeyUsage, MaxPathLen,
MaxPathLenZero, NotAfter, NotBefore, PermittedDNSDomains,
PermittedDNSDomainsCritical, SerialNumber, SignatureAlgorithm, Subject,
SubjectKeyId, and 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 signee
and priv is the private key of the signer.

The returned slice is the certificate in DER encoding.

All keys types that are implemented via crypto.Signer are supported (This
includes rsa.PublicKey and ecdsa.PublicKey.)

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

  1. 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: Attributes, DNSNames,
EmailAddresses, ExtraExtensions, IPAddresses, URIs, SignatureAlgorithm, and
Subject. The private key is the private key of the signer.

The returned slice is the certificate request in DER encoding.

All keys types that are implemented via crypto.Signer are supported (This
includes rsa.PublicKey and ecdsa.PublicKey.)

func DecryptPEMBlock

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

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

  1. func IsEncryptedPEMBlock(b *pem.Block) bool

IsEncryptedPEMBlock returns if the PEM block is password encrypted.

func MarshalECPrivateKey

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

MarshalECPrivateKey marshals an EC private key into ASN.1, DER format.

func MarshalPKCS1PrivateKey

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

MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.

func MarshalPKCS1PublicKey

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

MarshalPKCS1PublicKey converts an RSA public key to PKCS#1, ASN.1 DER form.

func MarshalPKCS8PrivateKey

  1. func MarshalPKCS8PrivateKey(key interface{}) ([]byte, error)

MarshalPKCS8PrivateKey converts a private key to PKCS#8 encoded form. The
following key types are supported: rsa.PrivateKey, ecdsa.PublicKey.
Unsupported key types result in an error.

See RFC 5208.

func MarshalPKIXPublicKey

  1. func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)

MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.

func ParseCRL

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

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

func ParseDERCRL

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

ParseDERCRL parses a DER encoded CRL from the given bytes.

func ParseECPrivateKey

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

ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.

func ParsePKCS1PrivateKey

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

ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER
encoded form.

func ParsePKCS1PublicKey

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

ParsePKCS1PublicKey parses a PKCS#1 public key in ASN.1 DER form.

func ParsePKCS8PrivateKey

  1. func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error)

ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See RFC 5208.

func ParsePKIXPublicKey

  1. func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)

ParsePKIXPublicKey parses a DER encoded public key. These values are typically
found in PEM blocks with “BEGIN PUBLIC KEY”.

Supported key types include RSA, DSA, and ECDSA. Unknown key types result in an
error.

On success, pub will be of type rsa.PublicKey, dsa.PublicKey, or
*ecdsa.PublicKey.


Example:

  1. const pubPEM = `
  2. -----BEGIN PUBLIC KEY-----
  3. MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlRuRnThUjU8/prwYxbty
  4. WPT9pURI3lbsKMiB6Fn/VHOKE13p4D8xgOCADpdRagdT6n4etr9atzDKUSvpMtR3
  5. CP5noNc97WiNCggBjVWhs7szEe8ugyqF23XwpHQ6uV1LKH50m92MbOWfCtjU9p/x
  6. qhNpQQ1AZhqNy5Gevap5k8XzRmjSldNAFZMY7Yv3Gi+nyCwGwpVtBUwhuLzgNFK/
  7. yDtw2WcWmUU7NuC8Q6MWvPebxVtCfVp/iQU6q60yyt6aGOBkhAX0LpKAEhKidixY
  8. nP9PNVBvxgu3XZ4P36gZV6+ummKdBVnc3NqwBLu5+CcdRdusmHPHd5pHf4/38Z3/
  9. 6qU2a/fPvWzceVTEgZ47QjFMTCTmCwNt29cvi7zZeQzjtwQgn4ipN9NibRH/Ax/q
  10. TbIzHfrJ1xa2RteWSdFjwtxi9C20HUkjXSeI4YlzQMH0fPX6KCE7aVePTOnB69I/
  11. a9/q96DiXZajwlpq3wFctrs1oXqBp5DVrCIj8hU2wNgB7LtQ1mCtsYz//heai0K9
  12. PhE4X6hiE0YmeAZjR0uHl8M/5aW9xCoJ72+12kKpWAa0SFRWLy6FejNYCYpkupVJ
  13. yecLk/4L1W0l6jQQZnWErXZYe0PNFcmwGXy1Rep83kfBRNKRy5tvocalLlwXLdUk
  14. AIU+2GKjyT3iMuzZxxFxPFMCAwEAAQ==
  15. -----END PUBLIC KEY-----`
  16. block, _ := pem.Decode([]byte(pubPEM))
  17. if block == nil {
  18. panic("failed to parse PEM block containing the public key")
  19. }
  20. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  21. if err != nil {
  22. panic("failed to parse DER encoded public key: " + err.Error())
  23. }
  24. switch pub := pub.(type) {
  25. case *rsa.PublicKey:
  26. fmt.Println("pub is of type RSA:", pub)
  27. case *dsa.PublicKey:
  28. fmt.Println("pub is of type DSA:", pub)
  29. case *ecdsa.PublicKey:
  30. fmt.Println("pub is of type ECDSA:", pub)
  31. default:
  32. panic("unknown type of public key")
  33. }

type CertPool

  1. type CertPool struct {
  2. // contains filtered or unexported fields
  3. }

CertPool is a set of certificates.

func NewCertPool

  1. func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

func SystemCertPool

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

func (*CertPool) AddCert

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

AddCert adds a certificate to a pool.

func (*CertPool) AppendCertsFromPEM

  1. func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)

AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. It
appends any certificates found to s and reports whether any certificates were
successfully parsed.

On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of
root CAs in a format suitable for this function.

func (*CertPool) Subjects

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

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

type Certificate

  1. type Certificate struct {
  2. Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
  3. RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
  4. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
  5. RawSubject []byte // DER encoded Subject
  6. RawIssuer []byte // DER encoded Issuer
  7.  
  8. Signature []byte
  9. SignatureAlgorithm SignatureAlgorithm
  10.  
  11. PublicKeyAlgorithm PublicKeyAlgorithm
  12. PublicKey interface{}
  13.  
  14. Version int
  15. SerialNumber *big.Int
  16. Issuer pkix.Name
  17. Subject pkix.Name
  18. NotBefore, NotAfter time.Time // Validity bounds.
  19. KeyUsage KeyUsage
  20.  
  21. // Extensions contains raw X.509 extensions. When parsing certificates,
  22. // this can be used to extract non-critical extensions that are not
  23. // parsed by this package. When marshaling certificates, the Extensions
  24. // field is ignored, see ExtraExtensions.
  25. Extensions []pkix.Extension
  26.  
  27. // ExtraExtensions contains extensions to be copied, raw, into any
  28. // marshaled certificates. Values override any extensions that would
  29. // otherwise be produced based on the other fields. The ExtraExtensions
  30. // field is not populated when parsing certificates, see Extensions.
  31. ExtraExtensions []pkix.Extension
  32.  
  33. // UnhandledCriticalExtensions contains a list of extension IDs that
  34. // were not (fully) processed when parsing. Verify will fail if this
  35. // slice is non-empty, unless verification is delegated to an OS
  36. // library which understands all the critical extensions.
  37. //
  38. // Users can access these extensions using Extensions and can remove
  39. // elements from this slice if they believe that they have been
  40. // handled.
  41. UnhandledCriticalExtensions []asn1.ObjectIdentifier
  42.  
  43. ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
  44. UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
  45.  
  46. // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
  47. // and MaxPathLenZero are valid.
  48. BasicConstraintsValid bool
  49. IsCA bool
  50.  
  51. // MaxPathLen and MaxPathLenZero indicate the presence and
  52. // value of the BasicConstraints' "pathLenConstraint".
  53. //
  54. // When parsing a certificate, a positive non-zero MaxPathLen
  55. // means that the field was specified, -1 means it was unset,
  56. // and MaxPathLenZero being true mean that the field was
  57. // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
  58. // should be treated equivalent to -1 (unset).
  59. //
  60. // When generating a certificate, an unset pathLenConstraint
  61. // can be requested with either MaxPathLen == -1 or using the
  62. // zero value for both MaxPathLen and MaxPathLenZero.
  63. MaxPathLen int
  64. // MaxPathLenZero indicates that BasicConstraintsValid==true
  65. // and MaxPathLen==0 should be interpreted as an actual
  66. // maximum path length of zero. Otherwise, that combination is
  67. // interpreted as MaxPathLen not being set.
  68. MaxPathLenZero bool
  69.  
  70. SubjectKeyId []byte
  71. AuthorityKeyId []byte
  72.  
  73. // RFC 5280, 4.2.2.1 (Authority Information Access)
  74. OCSPServer []string
  75. IssuingCertificateURL []string
  76.  
  77. // Subject Alternate Name values
  78. DNSNames []string
  79. EmailAddresses []string
  80. IPAddresses []net.IP
  81. URIs []*url.URL
  82.  
  83. // Name constraints
  84. PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
  85. PermittedDNSDomains []string
  86. ExcludedDNSDomains []string
  87. PermittedIPRanges []*net.IPNet
  88. ExcludedIPRanges []*net.IPNet
  89. PermittedEmailAddresses []string
  90. ExcludedEmailAddresses []string
  91. PermittedURIDomains []string
  92. ExcludedURIDomains []string
  93.  
  94. // CRL Distribution Points
  95. CRLDistributionPoints []string
  96.  
  97. PolicyIdentifiers []asn1.ObjectIdentifier
  98. }

A Certificate represents an X.509 certificate.

func ParseCertificate

  1. func ParseCertificate(asn1Data []byte) (*Certificate, error)

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

func (*Certificate) CheckCRLSignature

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

CheckCRLSignature checks that the signature in crl is from c.

func (*Certificate) CheckSignature

  1. 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 (*Certificate) CheckSignatureFrom

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

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

func (*Certificate) CreateCRL

  1. 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 (*Certificate) Equal

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

func (*Certificate) Verify

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

  1. // Verifying with a custom list of root certificates.
  2. const rootPEM = `
  3. -----BEGIN CERTIFICATE-----
  4. MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
  5. MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
  6. YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
  7. EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
  8. bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
  9. AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
  10. VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
  11. h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
  12. ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
  13. EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
  14. DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
  15. qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
  16. VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
  17. K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
  18. KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
  19. ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
  20. BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
  21. /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
  22. zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
  23. HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
  24. WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
  25. yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
  26. -----END CERTIFICATE-----`
  27. const certPEM = `
  28. -----BEGIN CERTIFICATE-----
  29. MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
  30. BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
  31. cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
  32. WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
  33. TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
  34. bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
  35. 5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
  36. 7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
  37. BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
  38. BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
  39. LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
  40. cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
  41. BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
  42. AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
  43. L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
  44. gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
  45. TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
  46. 0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
  47. RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
  48. yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
  49. -----END CERTIFICATE-----`
  50. // First, create the set of root certificates. For this example we only
  51. // have one. It's also possible to omit this in order to use the
  52. // default root set of the current operating system.
  53. roots := x509.NewCertPool()
  54. ok := roots.AppendCertsFromPEM([]byte(rootPEM))
  55. if !ok {
  56. panic("failed to parse root certificate")
  57. }
  58. block, _ := pem.Decode([]byte(certPEM))
  59. if block == nil {
  60. panic("failed to parse certificate PEM")
  61. }
  62. cert, err := x509.ParseCertificate(block.Bytes)
  63. if err != nil {
  64. panic("failed to parse certificate: " + err.Error())
  65. }
  66. opts := x509.VerifyOptions{
  67. DNSName: "mail.google.com",
  68. Roots: roots,
  69. }
  70. if _, err := cert.Verify(opts); err != nil {
  71. panic("failed to verify certificate: " + err.Error())
  72. }

func (*Certificate) VerifyHostname

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

type CertificateInvalidError

  1. type CertificateInvalidError struct {
  2. Cert *Certificate
  3. Reason InvalidReason
  4. Detail string
  5. }

CertificateInvalidError results when an odd error occurs. Users of this library
probably want to handle all these errors uniformly.

func (CertificateInvalidError) Error

  1. func (e CertificateInvalidError) Error() string

type CertificateRequest

  1. type CertificateRequest struct {
  2. Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  3. RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  4. RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
  5. RawSubject []byte // DER encoded Subject.
  6.  
  7. Version int
  8. Signature []byte
  9. SignatureAlgorithm SignatureAlgorithm
  10.  
  11. PublicKeyAlgorithm PublicKeyAlgorithm
  12. PublicKey interface{}
  13.  
  14. Subject pkix.Name
  15.  
  16. // Attributes is the dried husk of a bug and shouldn't be used.
  17. Attributes []pkix.AttributeTypeAndValueSET
  18.  
  19. // Extensions contains raw X.509 extensions. When parsing CSRs, this
  20. // can be used to extract extensions that are not parsed by this
  21. // package.
  22. Extensions []pkix.Extension
  23.  
  24. // ExtraExtensions contains extensions to be copied, raw, into any
  25. // marshaled CSR. Values override any extensions that would otherwise
  26. // be produced based on the other fields but are overridden by any
  27. // extensions specified in Attributes.
  28. //
  29. // The ExtraExtensions field is not populated when parsing CSRs, see
  30. // Extensions.
  31. ExtraExtensions []pkix.Extension
  32.  
  33. // Subject Alternate Name values.
  34. DNSNames []string
  35. EmailAddresses []string
  36. IPAddresses []net.IP
  37. URIs []*url.URL
  38. }

CertificateRequest represents a PKCS #10, certificate signature request.

func ParseCertificateRequest

  1. func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)

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

func (*CertificateRequest) CheckSignature

  1. func (c *CertificateRequest) CheckSignature() error

CheckSignature reports whether the signature on c is valid.

type ConstraintViolationError

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

  1. func (ConstraintViolationError) Error() string

type ExtKeyUsage

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

  1. const (
  2. ExtKeyUsageAny ExtKeyUsage = iota
  3. ExtKeyUsageServerAuth
  4. ExtKeyUsageClientAuth
  5. ExtKeyUsageCodeSigning
  6. ExtKeyUsageEmailProtection
  7. ExtKeyUsageIPSECEndSystem
  8. ExtKeyUsageIPSECTunnel
  9. ExtKeyUsageIPSECUser
  10. ExtKeyUsageTimeStamping
  11. ExtKeyUsageOCSPSigning
  12. ExtKeyUsageMicrosoftServerGatedCrypto
  13. ExtKeyUsageNetscapeServerGatedCrypto
  14. ExtKeyUsageMicrosoftCommercialCodeSigning
  15. ExtKeyUsageMicrosoftKernelCodeSigning
  16. )

type HostnameError

  1. type HostnameError struct {
  2. Certificate *Certificate
  3. Host string
  4. }

HostnameError results when the set of authorized names doesn’t match the
requested name.

func (HostnameError) Error

  1. func (h HostnameError) Error() string

type InsecureAlgorithmError

  1. type InsecureAlgorithmError SignatureAlgorithm

An InsecureAlgorithmError

func (InsecureAlgorithmError) Error

  1. func (e InsecureAlgorithmError) Error() string

type InvalidReason

  1. type InvalidReason int
  1. const (
  2. // NotAuthorizedToSign results when a certificate is signed by another
  3. // which isn't marked as a CA certificate.
  4. NotAuthorizedToSign InvalidReason = iota
  5. // Expired results when a certificate has expired, based on the time
  6. // given in the VerifyOptions.
  7. Expired
  8. // CANotAuthorizedForThisName results when an intermediate or root
  9. // certificate has a name constraint which doesn't permit a DNS or
  10. // other name (including IP address) in the leaf certificate.
  11. CANotAuthorizedForThisName
  12. // TooManyIntermediates results when a path length constraint is
  13. // violated.
  14. TooManyIntermediates
  15. // IncompatibleUsage results when the certificate's key usage indicates
  16. // that it may only be used for a different purpose.
  17. IncompatibleUsage
  18. // NameMismatch results when the subject name of a parent certificate
  19. // does not match the issuer name in the child.
  20. NameMismatch
  21. // NameConstraintsWithoutSANs results when a leaf certificate doesn't
  22. // contain a Subject Alternative Name extension, but a CA certificate
  23. // contains name constraints.
  24. NameConstraintsWithoutSANs
  25. // UnconstrainedName results when a CA certificate contains permitted
  26. // name constraints, but leaf certificate contains a name of an
  27. // unsupported or unconstrained type.
  28. UnconstrainedName
  29. // TooManyConstraints results when the number of comparision operations
  30. // needed to check a certificate exceeds the limit set by
  31. // VerifyOptions.MaxConstraintComparisions. This limit exists to
  32. // prevent pathological certificates can consuming excessive amounts of
  33. // CPU time to verify.
  34. TooManyConstraints
  35. // CANotAuthorizedForExtKeyUsage results when an intermediate or root
  36. // certificate does not permit an extended key usage that is claimed by
  37. // the leaf certificate.
  38. CANotAuthorizedForExtKeyUsage
  39. )

type KeyUsage

  1. type KeyUsage int

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

  1. const (
  2. KeyUsageDigitalSignature KeyUsage = 1 << iota
  3. KeyUsageContentCommitment
  4. KeyUsageKeyEncipherment
  5. KeyUsageDataEncipherment
  6. KeyUsageKeyAgreement
  7. KeyUsageCertSign
  8. KeyUsageCRLSign
  9. KeyUsageEncipherOnly
  10. KeyUsageDecipherOnly
  11. )

type PEMCipher

  1. type PEMCipher int
  1. const (
  2. PEMCipherDES PEMCipher
  3. PEMCipher3DES
  4. PEMCipherAES128
  5. PEMCipherAES192
  6. PEMCipherAES256
  7. )

Possible values for the EncryptPEMBlock encryption algorithm.

type PublicKeyAlgorithm

  1. type PublicKeyAlgorithm int
  1. const (
  2. UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
  3. RSA
  4. DSA
  5. ECDSA
  6. )

func (PublicKeyAlgorithm) String

  1. func (algo PublicKeyAlgorithm) String() string

type SignatureAlgorithm

  1. type SignatureAlgorithm int
  1. const (
  2. UnknownSignatureAlgorithm SignatureAlgorithm = iota
  3. MD2WithRSA
  4. MD5WithRSA
  5. SHA1WithRSA
  6. SHA256WithRSA
  7. SHA384WithRSA
  8. SHA512WithRSA
  9. DSAWithSHA1
  10. DSAWithSHA256
  11. ECDSAWithSHA1
  12. ECDSAWithSHA256
  13. ECDSAWithSHA384
  14. ECDSAWithSHA512
  15. SHA256WithRSAPSS
  16. SHA384WithRSAPSS
  17. SHA512WithRSAPSS
  18. )

func (SignatureAlgorithm) String

  1. func (algo SignatureAlgorithm) String() string

type SystemRootsError

  1. type SystemRootsError struct {
  2. Err error
  3. }

SystemRootsError results when we fail to load the system root certificates.

func (SystemRootsError) Error

  1. func (se SystemRootsError) Error() string

type UnhandledCriticalExtension

  1. type UnhandledCriticalExtension struct{}

func (UnhandledCriticalExtension) Error

  1. func (h UnhandledCriticalExtension) Error() string

type UnknownAuthorityError

  1. type UnknownAuthorityError struct {
  2. Cert *Certificate
  3. // contains filtered or unexported fields
  4. }

UnknownAuthorityError results when the certificate issuer is unknown

func (UnknownAuthorityError) Error

  1. func (e UnknownAuthorityError) Error() string

type VerifyOptions

  1. type VerifyOptions struct {
  2. DNSName string
  3. Intermediates *CertPool
  4. Roots *CertPool // if nil, the system roots are used
  5. CurrentTime time.Time // if zero, the current time is used
  6. // KeyUsage specifies which Extended Key Usage values are acceptable.
  7. // An empty list means ExtKeyUsageServerAuth. Key usage is considered a
  8. // constraint down the chain which mirrors Windows CryptoAPI behavior,
  9. // but not the spec. To accept any key usage, include ExtKeyUsageAny.
  10. KeyUsages []ExtKeyUsage
  11. // MaxConstraintComparisions is the maximum number of comparisons to
  12. // perform when checking a given certificate's name constraints. If
  13. // zero, a sensible default is used. This limit prevents pathalogical
  14. // certificates from consuming excessive amounts of CPU time when
  15. // validating.
  16. MaxConstraintComparisions int
  17. }

VerifyOptions contains parameters for Certificate.Verify. It’s a structure
because other PKIX verification APIs have ended up needing many options.

Subdirectories