Spec-Zone.ru › Go

Пакет x509

  • import "crypto/x509"
  • Обзор
  • Индекс
  • Примеры
  • Подкаталоги

Обзор

Пакет x509 реализует подмножество стандарта X.509.

Он позволяет разбирать и создавать сертификаты, запросы на подпись сертификата, списки отзыва сертификатов, а также закодированные открытые и закрытые ключи. В пакете есть средство проверки сертификатов с построителем цепочек.

Пакет ориентирован на технический профиль X.509, определённый IETF (RFC 2459/3280/5280) и дополнительно ограниченный базовыми требованиями CA/Browser Forum. Поддержка функций, выходящих за рамки этих профилей, минимальна, поскольку основная цель пакета — обеспечить совместимость с экосистемой общедоступных доверенных сертификатов TLS, а также её политиками и ограничениями.

В macOS и Windows проверка сертификатов выполняется системными API, однако пакет стремится применять единые правила проверки во всех операционных системах.

Индекс

  • Переменные
  • 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, priv crypto.Signer) ([]byte, error)
  • func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
  • func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
  • func IsEncryptedPEMBlock(b *pem.Block) bool
  • 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)
  • func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)
  • func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
  • func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
  • func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)
  • func ParsePKCS8PrivateKey(der []byte) (key any, err error)
  • func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)
  • func SetFallbackRoots(roots *CertPool)
  • type CertPool
  • func NewCertPool() *CertPool
  • func SystemCertPool() (*CertPool, error)
  • func (s *CertPool) AddCert(cert *Certificate)
  • func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)
  • func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
  • func (s *CertPool) Clone() *CertPool
  • func (s *CertPool) Equal(other *CertPool) bool
  • func (s *CertPool) Subjects() [][]byte
  • type Certificate
  • func ParseCertificate(der []byte) (*Certificate, error)
  • func ParseCertificates(der []byte) ([]*Certificate, error)
  • func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
  • func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
  • func (c *Certificate) CheckSignatureFrom(parent *Certificate) error
  • func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
  • func (c *Certificate) Equal(other *Certificate) bool
  • func (c *Certificate) Verify(opts VerifyOptions) ([][]*Certificate, error)
  • func (c *Certificate) VerifyHostname(h string) error
  • type CertificateInvalidError
  • func (e CertificateInvalidError) Error() string
  • type CertificateRequest
  • func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
  • func (c *CertificateRequest) CheckSignature() error
  • type ConstraintViolationError
  • func (ConstraintViolationError) Error() string
  • type ExtKeyUsage
  • func (eku ExtKeyUsage) OID() OID
  • func (i ExtKeyUsage) String() string
  • type HostnameError
  • func (h HostnameError) Error() string
  • type InsecureAlgorithmError
  • func (e InsecureAlgorithmError) Error() string
  • type InvalidReason
  • type KeyUsage
  • func (i KeyUsage) String() string
  • type OID
  • func OIDFromASN1OID(asn1OID asn1.ObjectIdentifier) (OID, error)
  • func OIDFromInts(oid []uint64) (OID, error)
  • func ParseOID(oid string) (OID, error)
  • func (o OID) AppendBinary(b []byte) ([]byte, error)
  • func (o OID) AppendText(b []byte) ([]byte, error)
  • func (oid OID) Equal(other OID) bool
  • func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool
  • func (o OID) MarshalBinary() ([]byte, error)
  • func (o OID) MarshalText() ([]byte, error)
  • func (oid OID) String() string
  • func (o *OID) UnmarshalBinary(b []byte) error
  • func (o *OID) UnmarshalText(text []byte) error
  • type PEMCipher
  • type PolicyMapping
  • type PublicKeyAlgorithm
  • func (algo PublicKeyAlgorithm) String() string
  • type RevocationList
  • func ParseRevocationList(der []byte) (*RevocationList, error)
  • func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error
  • type RevocationListEntry
  • type SignatureAlgorithm
  • func (algo SignatureAlgorithm) String() string
  • type SystemRootsError
  • func (se SystemRootsError) Error() string
  • func (se SystemRootsError) Unwrap() error
  • type UnhandledCriticalExtension
  • func (h UnhandledCriticalExtension) Error() string
  • type UnknownAuthorityError
  • func (e UnknownAuthorityError) Error() string
  • type VerifyOptions

Примеры

Certificate.Verify
MarshalPKCS8PrivateKey (MlDSA)
ParsePKIXPublicKey

Файлы пакета

cert_pool.go constraints.go oid.go parser.go pem_decrypt.go pkcs1.go pkcs8.go root.go root_linux.go root_unix.go sec1.go verify.go x509.go x509_string.go

Переменные

ErrUnsupportedAlgorithm возникает при попытке выполнить операцию с алгоритмами, которые в настоящее время не реализованы.

var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")

IncorrectPasswordError возвращается при обнаружении неверного пароля.

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

func CreateCertificate

func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)

CreateCertificate создает новый сертификат X.509 v3 на основе шаблона. В настоящее время используются следующие поля template:

  • 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 (см. примечание ниже)
  • Policies (см. примечание ниже)
  • SerialNumber
  • SignatureAlgorithm
  • Subject
  • SubjectKeyId
  • URIs
  • UnknownExtKeyUsage

Сертификат подписывается с помощью parent. Если parent совпадает с template, сертификат является самоподписанным. Параметр pub — это открытый ключ создаваемого сертификата, а priv — закрытый ключ подписывающего.

Возвращаемый срез содержит сертификат в кодировке DER.

В настоящее время поддерживаются следующие типы ключей: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey и *mldsa.PublicKey. pub должен иметь поддерживаемый тип ключа, а priv должен быть crypto.Signer или crypto.MessageSigner с поддерживаемым открытым ключом.

AuthorityKeyId будет взят из SubjectKeyId родительского сертификата, если он задан, кроме случая, когда создаваемый сертификат является самоподписанным. В противном случае будет использовано значение из template.

Если SubjectKeyId в template пуст, а template является сертификатом CA, SubjectKeyId будет сгенерирован на основе хеша открытого ключа.

Если template.SerialNumber равен nil, будет сгенерирован серийный номер, соответствующий RFC 5280, разделу 4.1.2.2, с использованием энтропии из rand.

Поля PolicyIdentifier и Policies можно использовать для маршалинга OID политик сертификата. По умолчанию маршалится только поле Policies, но если параметр GODEBUG "x509usepolicies" имеет значение "0", вместо поля Policies будет маршалиться поле PolicyIdentifiers. Это изменилось в Go 1.24. Поле Policies можно использовать для маршалинга OID политик, компоненты которых превышают 31 бит.

IP-адреса в IPAddresses, представленные в формате IPv6 с отображением IPv4, всегда будут кодироваться в формате IPv4.

func CreateCertificateRequest 1.3

func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)

CreateCertificateRequest создает новый запрос на сертификат на основе шаблона. Используются следующие поля template:

  • SignatureAlgorithm
  • Subject
  • DNSNames
  • EmailAddresses
  • IPAddresses
  • URIs
  • ExtraExtensions
  • Attributes (устарело)

priv — это закрытый ключ для подписи CSR, а соответствующий открытый ключ будет включен в CSR. Он должен реализовывать crypto.Signer или crypto.MessageSigner, а его метод Public() должен возвращать *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey или *mldsa.PublicKey. (Этому требованию удовлетворяют *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey и *mldsa.PrivateKey.)

Возвращаемый срез содержит запрос на сертификат в кодировке DER.

func CreateRevocationList 1.15

func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)

CreateRevocationList создает новый список отзыва сертификатов X.509 v2 Certificate в соответствии с RFC 5280 на основе template.

CRL подписывается с помощью priv, который должен быть crypto.Signer или crypto.MessageSigner, связанным с открытым ключом сертификата издателя.

issuer не может быть nil, а для использования сертификата в качестве издателя CRL в KeyUsage должен быть установлен бит crlSign.

Поле имени различаемого издателя в CRL и расширение идентификатора ключа центра сертификации заполняются с использованием сертификата издателя. У issuer должен быть задан SubjectKeyId.

func DecryptPEMBlock 1.1

func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)

DecryptPEMBlock принимает блок PEM, зашифрованный в соответствии с RFC 1423, и пароль, использованный для его шифрования, и возвращает срез расшифрованных байтов в кодировке DER. Функция проверяет заголовок DEK-Info, чтобы определить алгоритм расшифрования. Если заголовок DEK-Info отсутствует, возвращается ошибка. Если обнаружен неверный пароль, возвращается IncorrectPasswordError. Из-за недостатков формата не всегда возможно обнаружить неверный пароль. В таких случаях ошибка не возвращается, но расшифрованные байты DER будут содержать случайный шум.

Устарело: устаревшее шифрование PEM, определенное в RFC 1423, по своей конструкции небезопасно. Поскольку оно не обеспечивает аутентификацию шифротекста, оно уязвимо для атак с оракулом дополнения, которые могут позволить злоумышленнику восстановить открытый текст.

func EncryptPEMBlock 1.1

func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)

EncryptPEMBlock возвращает блок PEM указанного типа, содержащий заданные данные в кодировке DER, зашифрованные указанным алгоритмом и паролем в соответствии с RFC 1423.

Устарело: устаревшее шифрование PEM, определенное в RFC 1423, по своей конструкции небезопасно. Поскольку оно не обеспечивает аутентификацию шифротекста, оно уязвимо для атак с оракулом дополнения, которые могут позволить злоумышленнику восстановить открытый текст.

func IsEncryptedPEMBlock 1.1

func IsEncryptedPEMBlock(b *pem.Block) bool

IsEncryptedPEMBlock возвращает признак того, что блок PEM зашифрован паролем в соответствии с RFC 1423.

Устарело: устаревшее шифрование PEM, определенное в RFC 1423, по своей конструкции небезопасно. Поскольку оно не обеспечивает аутентификацию шифротекста, оно уязвимо для атак с оракулом дополнения, которые могут позволить злоумышленнику восстановить открытый текст.

func MarshalECPrivateKey 1.2

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

MarshalECPrivateKey преобразует закрытый ключ EC в формат SEC 1 ASN.1 DER.

Ключи такого типа обычно кодируются в блоках PEM с типом "EC PRIVATE KEY". Для более гибкого формата ключей, не ограниченного EC, используйте MarshalPKCS8PrivateKey.

func MarshalPKCS1PrivateKey

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

MarshalPKCS1PrivateKey преобразует закрытый ключ RSA в формат PKCS #1, ASN.1 DER.

Ключи этого типа обычно кодируются в PEM-блоках типа "RSA PRIVATE KEY". Для более гибкого формата ключа, не специфичного для RSA, используйте MarshalPKCS8PrivateKey.

Сначала ключ необходимо проверить, вызвав rsa.PrivateKey.Validate. MarshalPKCS1PrivateKey вызывает rsa.PrivateKey.Precompute, который может изменить ключ, если предварительные вычисления ещё не были выполнены.

func MarshalPKCS1PublicKey 1.10

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

MarshalPKCS1PublicKey преобразует открытый ключ RSA в формат PKCS #1, ASN.1 DER.

Ключи этого типа обычно кодируются в PEM-блоках типа "RSA PUBLIC KEY".

func MarshalPKCS8PrivateKey 1.10

func MarshalPKCS8PrivateKey(key any) ([]byte, error)

MarshalPKCS8PrivateKey преобразует закрытый ключ в формат PKCS #8, ASN.1 DER.

В настоящее время поддерживаются следующие типы ключей: *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey (не указатель), *mldsa.PrivateKey и *ecdh.PrivateKey. Для неподдерживаемых типов ключей возвращается ошибка.

Ключи этого типа обычно кодируются в PEM-блоках типа "PRIVATE KEY".

Для ключей RSA MarshalPKCS8PrivateKey выполняет rsa.PrivateKey.Precompute.

Пример (MlDSA)

Код:

// Generate an ML-DSA-44 key, marshal it to PKCS #8, and PEM-encode it.
// ML-DSA private keys are encoded in their seed-only representation per
// RFC 9881.
priv, err := mldsa.GenerateKey(mldsa.MLDSA44())
if err != nil {
    panic(err)
}

der, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
    panic(err)
}

pemBytes := pem.EncodeToMemory(&pem.Block{
    Type:  "PRIVATE KEY",
    Bytes: der,
})

// Round-trip the PEM-encoded key back into an *mldsa.PrivateKey.
block, _ := pem.Decode(pemBytes)
if block == nil {
    panic("failed to decode PEM block")
}
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
    panic(err)
}
if !parsed.(*mldsa.PrivateKey).Equal(priv) {
    panic("round-tripped key does not match original")
}

func MarshalPKIXPublicKey

func MarshalPKIXPublicKey(pub any) ([]byte, error)

MarshalPKIXPublicKey преобразует открытый ключ в формат PKIX, ASN.1 DER. Закодированный открытый ключ представляет собой структуру SubjectPublicKeyInfo (см. RFC 5280, раздел 4.1).

В настоящее время поддерживаются следующие типы ключей: *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (не указатель), *mldsa.PublicKey и *ecdh.PublicKey. Для неподдерживаемых типов ключей возвращается ошибка.

Ключи этого типа обычно кодируются в PEM-блоках типа "PUBLIC KEY".

func ParseCRL

func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)

ParseCRL разбирает список отзыва сертификатов (CRL) из заданных байтов. Нередко CRL, закодированные в PEM, встречаются там, где ожидается кодировка DER, поэтому эта функция автоматически обрабатывает кодировку PEM, если перед данными нет посторонних байтов.

Устарело: вместо этого используйте ParseRevocationList.

func ParseDERCRL

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

ParseDERCRL разбирает список отзыва сертификатов (CRL), закодированный в DER, из заданных байтов.

Устарело: вместо этого используйте ParseRevocationList.

func ParseECPrivateKey 1.1

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

ParseECPrivateKey разбирает закрытый ключ EC в формате SEC 1, ASN.1 DER.

Ключи этого типа обычно кодируются в PEM-блоках типа "EC PRIVATE KEY".

func ParsePKCS1PrivateKey

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

ParsePKCS1PrivateKey разбирает закрытый ключ RSA в формате PKCS #1, ASN.1 DER.

Ключи этого типа обычно кодируются в PEM-блоках типа "RSA PRIVATE KEY".

До Go 1.24 параметры CRT игнорировались и вычислялись заново. Чтобы восстановить прежнее поведение, используйте переменную среды GODEBUG=x509rsacrt=0.

func ParsePKCS1PublicKey 1.10

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

ParsePKCS1PublicKey разбирает открытый ключ RSA в формате PKCS #1, ASN.1 DER.

Ключи этого типа обычно кодируются в PEM-блоках типа "RSA PUBLIC KEY".

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der []byte) (key any, err error)

ParsePKCS8PrivateKey разбирает незашифрованный закрытый ключ в формате PKCS #8, ASN.1 DER.

Функция возвращает *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey (не указатель), *mldsa.PrivateKey или *ecdh.PrivateKey (для X25519). В будущем могут поддерживаться и другие типы.

Ключи этого типа обычно кодируются в PEM-блоках типа "PRIVATE KEY".

До Go 1.24 параметры CRT ключей RSA игнорировались и вычислялись заново. Чтобы восстановить прежнее поведение, используйте переменную среды GODEBUG=x509rsacrt=0.

func ParsePKIXPublicKey

func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)

ParsePKIXPublicKey разбирает открытый ключ в формате PKIX, ASN.1 DER. Закодированный открытый ключ представляет собой структуру SubjectPublicKeyInfo (см. RFC 5280, раздел 4.1).

Функция возвращает *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey (не указатель), *mldsa.PublicKey или *ecdh.PublicKey (для X25519). В будущем могут поддерживаться и другие типы.

Ключи этого типа обычно кодируются в PEM-блоках типа "PUBLIC KEY".

Пример

Код:

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)
case *mldsa.PublicKey:
    fmt.Println("pub is of type ML-DSA:", pub)
default:
    panic("unknown type of public key")
}

func SetFallbackRoots 1.20

func SetFallbackRoots(roots *CertPool)

SetFallbackRoots задаёт корневые сертификаты, используемые при проверке сертификатов, если пользовательские корневые сертификаты не заданы, а проверяющий механизм платформы или системный пул сертификатов недоступен (например, в контейнере без набора корневых сертификатов). Если roots равен nil, SetFallbackRoots вызывает панику.

SetFallbackRoots можно вызвать только один раз; повторный вызов приведёт к панике.

Резервное поведение можно принудительно включить на всех платформах, даже если системный пул сертификатов доступен, задав GODEBUG=x509usefallbackroots=1 (обратите внимание: в Windows и macOS это отключит использование API проверки платформы, и будет применяться механизм проверки на чистом Go). Установка x509usefallbackroots=1 без вызова SetFallbackRoots ни на что не влияет.

type CertPool

CertPool — это набор сертификатов.

type CertPool struct {
    // contains filtered or unexported fields
}

func NewCertPool

func NewCertPool() *CertPool

NewCertPool возвращает новый пустой CertPool.

func SystemCertPool 1.7

func SystemCertPool() (*CertPool, error)

SystemCertPool возвращает копию системного пула сертификатов.

Переменные среды SSL_CERT_FILE и SSL_CERT_DIR позволяют переопределить стандартные системные расположения файла сертификатов SSL и каталога файлов сертификатов SSL соответственно. Последняя переменная может содержать список, разделённый двоеточиями, а в Windows — список, разделённый точками с запятой. На платформах, имеющих системные API для проверки сертификатов (macOS и Windows), установка SSL_CERT_FILE или SSL_CERT_DIR предотвращает использование этих API, если не задан параметр GODEBUG x509sslcertoverrideplatform=0. (Это изменилось в Go 1.27.)

Изменения, внесённые в возвращённый пул, не записываются на диск и не влияют на другие пулы, возвращаемые SystemCertPool.

Новые изменения в системном пуле сертификатов могут не отражаться в последующих вызовах.

func (*CertPool) AddCert

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

AddCert добавляет сертификат в пул.

func (*CertPool) AddCertWithConstraint 1.22

func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)

AddCertWithConstraint добавляет сертификат в пул с дополнительным ограничением. Когда Certificate.Verify строит цепочку, корнем которой является cert, он дополнительно передаёт всю цепочку в constraint, чтобы определить её допустимость. Если constraint возвращает ненулевую ошибку, цепочка будет отброшена. constraint может вызываться одновременно из нескольких горутин.

func (*CertPool) AppendCertsFromPEM

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

AppendCertsFromPEM пытается разобрать последовательность сертификатов в кодировке PEM. Он добавляет все найденные сертификаты в s и сообщает, удалось ли разобрать хотя бы один сертификат.

Во многих системах Linux файл /etc/ssl/cert.pem содержит общесистемный набор корневых центров сертификации в формате, подходящем для этой функции.

func (*CertPool) Clone 1.19

func (s *CertPool) Clone() *CertPool

Clone возвращает копию s.

func (*CertPool) Equal 1.19

func (s *CertPool) Equal(other *CertPool) bool

Equal сообщает, равны ли s и other.

func (*CertPool) Subjects

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

Subjects возвращает список субъектов всех сертификатов в пуле, закодированных в формате DER.

Устарело: если s был возвращён функцией SystemCertPool, Subjects не будет включать системные корневые сертификаты.

type Certificate

Certificate представляет сертификат X.509.

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
    RawSignatureAlgorithm   []byte // DER encoded AlgorithmIdentifier; added in Go 1.27

    Signature          []byte
    SignatureAlgorithm SignatureAlgorithm

    PublicKeyAlgorithm PublicKeyAlgorithm
    PublicKey          any

    Version             int
    SerialNumber        *big.Int
    Issuer              pkix.Name
    Subject             pkix.Name
    NotBefore, NotAfter time.Time // Validity bounds.
    KeyUsage            KeyUsage

    // Extensions contains raw X.509 extensions. When parsing certificates,
    // this can be used to extract non-critical extensions that are not
    // parsed by this package. When marshaling certificates, the Extensions
    // field is ignored, see ExtraExtensions.
    Extensions []pkix.Extension // Go 1.2

    // 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 // Go 1.2

    // 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 // Go 1.5

    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 // Go 1.4

    SubjectKeyId   []byte
    AuthorityKeyId []byte

    // RFC 5280, 4.2.2.1 (Authority Information Access)
    OCSPServer            []string // Go 1.2
    IssuingCertificateURL []string // Go 1.2

    // 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 // Go 1.1
    URIs           []*url.URL // Go 1.10

    // Name constraints
    PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
    PermittedDNSDomains         []string
    ExcludedDNSDomains          []string // Go 1.9
    PermittedIPRanges           []*net.IPNet // Go 1.10
    ExcludedIPRanges            []*net.IPNet // Go 1.10
    PermittedEmailAddresses     []string // Go 1.10
    ExcludedEmailAddresses      []string // Go 1.10
    PermittedURIDomains         []string // Go 1.10
    ExcludedURIDomains          []string // Go 1.10

    // CRL Distribution Points
    CRLDistributionPoints []string // Go 1.2

    // PolicyIdentifiers contains asn1.ObjectIdentifiers, the components
    // of which are limited to int32. If a certificate contains a policy which
    // cannot be represented by asn1.ObjectIdentifier, it will not be included in
    // PolicyIdentifiers, but will be present in Policies, which contains all parsed
    // policy OIDs.
    // See CreateCertificate for context about how this field and the Policies field
    // interact.
    PolicyIdentifiers []asn1.ObjectIdentifier

    // Policies contains all policy identifiers included in the certificate.
    // See CreateCertificate for context about how this field and the PolicyIdentifiers field
    // interact.
    // In Go 1.22, encoding/gob cannot handle and ignores this field.
    Policies []OID // Go 1.22

    // InhibitAnyPolicy and InhibitAnyPolicyZero indicate the presence and value
    // of the inhibitAnyPolicy extension.
    //
    // The value of InhibitAnyPolicy indicates the number of additional
    // certificates in the path after this certificate that may use the
    // anyPolicy policy OID to indicate a match with any other policy.
    //
    // When parsing a certificate, a positive non-zero InhibitAnyPolicy means
    // that the field was specified, -1 means it was unset, and
    // InhibitAnyPolicyZero being true mean that the field was explicitly set to
    // zero. The case of InhibitAnyPolicy==0 with InhibitAnyPolicyZero==false
    // should be treated equivalent to -1 (unset).
    InhibitAnyPolicy int // Go 1.24
    // InhibitAnyPolicyZero indicates that InhibitAnyPolicy==0 should be
    // interpreted as an actual maximum path length of zero. Otherwise, that
    // combination is interpreted as InhibitAnyPolicy not being set.
    InhibitAnyPolicyZero bool // Go 1.24

    // InhibitPolicyMapping and InhibitPolicyMappingZero indicate the presence
    // and value of the inhibitPolicyMapping field of the policyConstraints
    // extension.
    //
    // The value of InhibitPolicyMapping indicates the number of additional
    // certificates in the path after this certificate that may use policy
    // mapping.
    //
    // When parsing a certificate, a positive non-zero InhibitPolicyMapping
    // means that the field was specified, -1 means it was unset, and
    // InhibitPolicyMappingZero being true mean that the field was explicitly
    // set to zero. The case of InhibitPolicyMapping==0 with
    // InhibitPolicyMappingZero==false should be treated equivalent to -1
    // (unset).
    InhibitPolicyMapping int // Go 1.24
    // InhibitPolicyMappingZero indicates that InhibitPolicyMapping==0 should be
    // interpreted as an actual maximum path length of zero. Otherwise, that
    // combination is interpreted as InhibitAnyPolicy not being set.
    InhibitPolicyMappingZero bool // Go 1.24

    // RequireExplicitPolicy and RequireExplicitPolicyZero indicate the presence
    // and value of the requireExplicitPolicy field of the policyConstraints
    // extension.
    //
    // The value of RequireExplicitPolicy indicates the number of additional
    // certificates in the path after this certificate before an explicit policy
    // is required for the rest of the path. When an explicit policy is required,
    // each subsequent certificate in the path must contain a required policy OID,
    // or a policy OID which has been declared as equivalent through the policy
    // mapping extension.
    //
    // When parsing a certificate, a positive non-zero RequireExplicitPolicy
    // means that the field was specified, -1 means it was unset, and
    // RequireExplicitPolicyZero being true mean that the field was explicitly
    // set to zero. The case of RequireExplicitPolicy==0 with
    // RequireExplicitPolicyZero==false should be treated equivalent to -1
    // (unset).
    RequireExplicitPolicy int // Go 1.24
    // RequireExplicitPolicyZero indicates that RequireExplicitPolicy==0 should be
    // interpreted as an actual maximum path length of zero. Otherwise, that
    // combination is interpreted as InhibitAnyPolicy not being set.
    RequireExplicitPolicyZero bool // Go 1.24

    // PolicyMappings contains a list of policy mappings included in the certificate.
    PolicyMappings []PolicyMapping // Go 1.24
}

func ParseCertificate

func ParseCertificate(der []byte) (*Certificate, error)

ParseCertificate разбирает один сертификат из предоставленных данных ASN.1 DER.

До Go 1.23 функция ParseCertificate принимала сертификаты с отрицательными серийными номерами. Это поведение можно восстановить, добавив "x509negativeserial=1" в переменную окружения GODEBUG.

func ParseCertificates

func ParseCertificates(der []byte) ([]*Certificate, error)

ParseCertificates разбирает один или несколько сертификатов из предоставленных данных ASN.1 DER. Сертификаты должны быть объединены без промежуточных заполнителей.

func (*Certificate) CheckCRLSignature

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

CheckCRLSignature проверяет, что подпись в crl создана c.

Устарело: вместо этого используйте RevocationList.CheckSignatureFrom.

func (*Certificate) CheckSignature

func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error

CheckSignature проверяет, является ли signature допустимой подписью данных signed, созданной открытым ключом c.

Это низкоуровневый API, который не выполняет проверку действительности сертификата.

Подписи MD5WithRSA отклоняются, тогда как подписи SHA1WithRSA и ECDSAWithSHA1 в настоящее время принимаются.

func (*Certificate) CheckSignatureFrom

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

CheckSignatureFrom проверяет, является ли подпись сертификата c допустимой подписью, созданной parent.

Это низкоуровневый API, который выполняет очень ограниченную проверку, а не полную проверку пути сертификации. Большинству пользователей следует вместо этого использовать Certificate.Verify.

func (*Certificate) CreateCRL

func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)

CreateCRL возвращает CRL в кодировке DER, подписанный этим сертификатом и содержащий указанный список отозванных сертификатов.

Устарело: этот метод не создаёт CRL версии 2 X.509, соответствующий RFC 5280. Для создания CRL, соответствующего стандартам, используйте вместо этого CreateRevocationList.

func (*Certificate) Equal

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

func (*Certificate) Verify

func (c *Certificate) Verify(opts VerifyOptions) ([][]*Certificate, error)

Verify пытается проверить c, построив одну или несколько цепочек от c до сертификата из opts.Roots и при необходимости используя сертификаты из opts.Intermediates. В случае успеха функция возвращает одну или несколько цепочек, в которых первым элементом является c, а последним — сертификат из opts.Roots.

Если opts.Roots равен nil, может использоваться системный механизм проверки, и детали проверки могут отличаться от описанных ниже. Если системные корневые сертификаты недоступны, возвращённая ошибка будет иметь тип SystemRootsError.

Ограничения на имена, заданные в промежуточных сертификатах, применяются ко всем именам, указанным в цепочке, а не только к opts.DNSName. Поэтому недопустимо, чтобы конечный сертификат указывал example.com, если промежуточный сертификат не разрешает это имя, даже если example.com не является проверяемым именем. Обратите внимание, что ограничения DirectoryName не поддерживаются.

Проверка ограничений на имена выполняется по правилам RFC 5280, с дополнительным условием: ограничения на DNS-имена могут использовать начальную точку, как и ограничения для адресов электронной почты и URI. Начальная точка в ограничении означает, что перед ограниченным именем должна быть добавлена как минимум одна дополнительная метка, чтобы имя считалось допустимым.

Значения Extended Key Usage проверяются для всей цепочки: если промежуточный или корневой сертификат перечисляет EKU, конечный сертификат не может указывать EKU, отсутствующий в этом списке. (Хотя это не предусмотрено спецификацией, такая практика широко распространена и позволяет ограничить типы сертификатов, которые может выдавать центр сертификации.)

Сертификаты с подписями SHA1WithRSA и ECDSAWithSHA1 не поддерживаются и не будут использоваться для построения цепочек.

Не следует изменять сертификаты в возвращённых цепочках, кроме c.

ПРЕДУПРЕЖДЕНИЕ: эта функция не выполняет проверку отзыва сертификатов.

Пример

Код:

// 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())
}

func (*Certificate) VerifyHostname

func (c *Certificate) VerifyHostname(h string) error

VerifyHostname возвращает nil, если c является допустимым сертификатом для указанного узла. В противном случае функция возвращает ошибку с описанием несоответствия.

IP-адреса можно при необходимости заключить в квадратные скобки; они проверяются по полю IPAddresses. Другие имена проверяются без учёта регистра по полю DNSNames. Если имена являются допустимыми именами узлов, в полях сертификата вместо самой левой метки целиком может использоваться подстановочный знак (например, *.example.com).

Обратите внимание, что устаревшее поле Common Name игнорируется.

type CertificateInvalidError

CertificateInvalidError возникает при необычной ошибке. Пользователям этой библиотеки, вероятно, следует обрабатывать все такие ошибки единообразно.

type CertificateInvalidError struct {
    Cert   *Certificate
    Reason InvalidReason
    Detail string // Go 1.10
}

func (CertificateInvalidError) Error

func (e CertificateInvalidError) Error() string

type CertificateRequest 1.3

CertificateRequest представляет запрос на подпись сертификата PKCS #10.

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.
    RawSignatureAlgorithm    []byte // DER encoded AlgorithmIdentifier; added in Go 1.27

    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           []*url.URL // Go 1.10
}

func ParseCertificateRequest 1.3

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

ParseCertificateRequest разбирает один запрос на сертификат из предоставленных данных ASN.1 DER.

func (*CertificateRequest) CheckSignature 1.5

func (c *CertificateRequest) CheckSignature() error

CheckSignature сообщает, является ли подпись в c допустимой.

type ConstraintViolationError

ConstraintViolationError возникает, когда запрошенное использование не разрешено сертификатом. Например, при проверке подписи, если открытый ключ не предназначен для подписи сертификатов.

type ConstraintViolationError struct{}

func (ConstraintViolationError) Error

func (ConstraintViolationError) Error() string

type ExtKeyUsage

ExtKeyUsage представляет расширенный набор действий, допустимых для данного ключа. Каждая из констант ExtKeyUsage* определяет уникальное действие.

type ExtKeyUsage int
const (
    ExtKeyUsageAny                            ExtKeyUsage = iota // anyExtendedKeyUsage
    ExtKeyUsageServerAuth                                        // serverAuth
    ExtKeyUsageClientAuth                                        // clientAuth
    ExtKeyUsageCodeSigning                                       // codeSigning
    ExtKeyUsageEmailProtection                                   // emailProtection
    ExtKeyUsageIPSECEndSystem                                    // ipsecEndSystem
    ExtKeyUsageIPSECTunnel                                       // ipsecTunnel
    ExtKeyUsageIPSECUser                                         // ipsecUser
    ExtKeyUsageTimeStamping                                      // timeStamping
    ExtKeyUsageOCSPSigning                                       // OCSPSigning
    ExtKeyUsageMicrosoftServerGatedCrypto                        // msSGC
    ExtKeyUsageNetscapeServerGatedCrypto                         // nsSGC
    ExtKeyUsageMicrosoftCommercialCodeSigning                    // msCodeCom
    ExtKeyUsageMicrosoftKernelCodeSigning                        // msKernelCode
)

func (ExtKeyUsage) OID 1.26

func (eku ExtKeyUsage) OID() OID

OID возвращает идентификатор объекта ASN.1 для EKU.

func (ExtKeyUsage) String 1.26

func (i ExtKeyUsage) String() string

type HostnameError

HostnameError возникает, когда набор авторизованных имён не соответствует запрошенному имени.

type HostnameError struct {
    Certificate *Certificate
    Host        string
}

func (HostnameError) Error

func (h HostnameError) Error() string

type InsecureAlgorithmError 1.6

InsecureAlgorithmError указывает, что используемый для создания подписи SignatureAlgorithm является небезопасным и подпись была отклонена.

type InsecureAlgorithmError SignatureAlgorithm

func (InsecureAlgorithmError) Error 1.6

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
    // TooManyIntermediates results when a path length constraint is
    // violated.
    TooManyIntermediates
    // IncompatibleUsage results when the certificate's key usage indicates
    // that it may only be used for a different purpose.
    IncompatibleUsage
    // NameMismatch results when the subject name of a parent certificate
    // does not match the issuer name in the child.
    NameMismatch
    // NameConstraintsWithoutSANs is a legacy error and is no longer returned.
    NameConstraintsWithoutSANs
    // UnconstrainedName results when a CA certificate contains permitted
    // name constraints, but leaf certificate contains a name of an
    // unsupported or unconstrained type.
    UnconstrainedName
    // TooManyConstraints results when the number of comparison operations
    // needed to check a certificate exceeds the limit set by
    // VerifyOptions.MaxConstraintComparisions. This limit exists to
    // prevent pathological certificates can consuming excessive amounts of
    // CPU time to verify.
    TooManyConstraints
    // CANotAuthorizedForExtKeyUsage results when an intermediate or root
    // certificate does not permit a requested extended key usage.
    CANotAuthorizedForExtKeyUsage
    // NoValidChains results when there are no valid chains to return.
    NoValidChains
)

type KeyUsage

KeyUsage представляет набор действий, допустимых для данного ключа. Это битовая маска констант KeyUsage*.

type KeyUsage int
const (
    KeyUsageDigitalSignature  KeyUsage = 1 << iota // digitalSignature
    KeyUsageContentCommitment                      // contentCommitment
    KeyUsageKeyEncipherment                        // keyEncipherment
    KeyUsageDataEncipherment                       // dataEncipherment
    KeyUsageKeyAgreement                           // keyAgreement
    KeyUsageCertSign                               // keyCertSign
    KeyUsageCRLSign                                // cRLSign
    KeyUsageEncipherOnly                           // encipherOnly
    KeyUsageDecipherOnly                           // decipherOnly
)

func (KeyUsage) String 1.26

func (i KeyUsage) String() string

type OID 1.22

OID представляет идентификатор объекта ASN.1 (OBJECT IDENTIFIER).

type OID struct {
    // contains filtered or unexported fields
}

func OIDFromASN1OID 1.26

func OIDFromASN1OID(asn1OID asn1.ObjectIdentifier) (OID, error)

OIDFromASN1OID создаёт новый OID, используя asn1OID.

func OIDFromInts 1.22

func OIDFromInts(oid []uint64) (OID, error)

OIDFromInts создаёт новый OID, используя ints; каждое целое число является отдельным компонентом.

func ParseOID 1.23

func ParseOID(oid string) (OID, error)

ParseOID разбирает строку идентификатора объекта, представленную ASCII-числами, разделёнными точками.

func (OID) AppendBinary 1.24

func (o OID) AppendBinary(b []byte) ([]byte, error)

AppendBinary реализует encoding.BinaryAppender

func (OID) AppendText 1.24

func (o OID) AppendText(b []byte) ([]byte, error)

AppendText реализует encoding.TextAppender

func (OID) Equal 1.22

func (oid OID) Equal(other OID) bool

Equal возвращает true, если oid и other представляют один и тот же идентификатор объекта.

func (OID) EqualASN1OID 1.22

func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool

EqualASN1OID возвращает, равен ли OID значению asn1.ObjectIdentifier. Если asn1.ObjectIdentifier не может представить идентификатор, указанный в oid, поскольку для одного из компонентов OID требуется более 31 бита, возвращается false.

func (OID) MarshalBinary 1.23

func (o OID) MarshalBinary() ([]byte, error)

MarshalBinary реализует encoding.BinaryMarshaler

func (OID) MarshalText 1.23

func (o OID) MarshalText() ([]byte, error)

MarshalText реализует encoding.TextMarshaler

func (OID) String 1.22

func (oid OID) String() string

String возвращает строковое представление идентификатора объекта.

func (*OID) UnmarshalBinary 1.23

func (o *OID) UnmarshalBinary(b []byte) error

UnmarshalBinary реализует encoding.BinaryUnmarshaler

func (*OID) UnmarshalText 1.23

func (o *OID) UnmarshalText(text []byte) error

UnmarshalText реализует encoding.TextUnmarshaler

type PEMCipher 1.1

type PEMCipher int

Возможные значения для алгоритма шифрования EncryptPEMBlock.

const (
    PEMCipherDES PEMCipher
    PEMCipher3DES
    PEMCipherAES128
    PEMCipherAES192
    PEMCipherAES256
)

type PolicyMapping 1.24

PolicyMapping представляет запись сопоставления политик в расширении policyMappings.

type PolicyMapping struct {
    // IssuerDomainPolicy contains a policy OID the issuing certificate considers
    // equivalent to SubjectDomainPolicy in the subject certificate.
    IssuerDomainPolicy OID
    // SubjectDomainPolicy contains a OID the issuing certificate considers
    // equivalent to IssuerDomainPolicy in the subject certificate.
    SubjectDomainPolicy OID
}

type PublicKeyAlgorithm

type PublicKeyAlgorithm int
const (
    UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
    RSA
    DSA // Only supported for parsing.
    ECDSA
    Ed25519
    MLDSA
)

func (PublicKeyAlgorithm) String 1.10

func (algo PublicKeyAlgorithm) String() string

type RevocationList 1.15

RevocationList представляет список отзыва сертификатов (CRL), определённый в RFC 5280, в виде Certificate.

type RevocationList struct {
    // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
    // signatureAlgorithm, and signatureValue.)
    Raw []byte // Go 1.19
    // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
    // DER.
    RawTBSRevocationList []byte // Go 1.19
    // RawIssuer contains the DER encoded Issuer.
    RawIssuer []byte // Go 1.19
    // RawSignatureAlgorithm contains the DER encoded signature algorithm as a
    // PKIX AlgorithmIdentifier.
    RawSignatureAlgorithm []byte // Go 1.27

    // Issuer contains the DN of the issuing certificate.
    Issuer pkix.Name // Go 1.19
    // 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 // Go 1.19

    Signature []byte // Go 1.19
    // 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 // Go 1.21

    // 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 // Go 1.19

    // ExtraExtensions contains any additional extensions to add directly to
    // the CRL.
    ExtraExtensions []pkix.Extension
}

func ParseRevocationList 1.19

func ParseRevocationList(der []byte) (*RevocationList, error)

ParseRevocationList разбирает список отзыва сертификатов X.509 версии 2 из предоставленных данных ASN.1 DER.

func (*RevocationList) CheckSignatureFrom 1.19

func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error

CheckSignatureFrom проверяет, является ли подпись rl действительной подписью issuer.

type RevocationListEntry 1.21

RevocationListEntry представляет запись в последовательности revokedCertificates списка CRL.

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
}

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
    MLDSA44
    MLDSA65
    MLDSA87
)

func (SignatureAlgorithm) String 1.6

func (algo SignatureAlgorithm) String() string

type SystemRootsError 1.1

SystemRootsError возникает, когда не удаётся загрузить системные корневые сертификаты.

type SystemRootsError struct {
    Err error // Go 1.7
}

func (SystemRootsError) Error 1.1

func (se SystemRootsError) Error() string

func (SystemRootsError) Unwrap 1.16

func (se SystemRootsError) Unwrap() error

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct{}

func (UnhandledCriticalExtension) Error

func (h UnhandledCriticalExtension) Error() string

type UnknownAuthorityError

UnknownAuthorityError возникает, когда издатель сертификата неизвестен

type UnknownAuthorityError struct {
    Cert *Certificate // Go 1.8
    // contains filtered or unexported fields
}

func (UnknownAuthorityError) Error

func (e UnknownAuthorityError) Error() string

type VerifyOptions

VerifyOptions содержит параметры для Certificate.Verify.

type VerifyOptions struct {
    // DNSName, if set, is checked against the leaf certificate with
    // Certificate.VerifyHostname or the platform verifier.
    DNSName string

    // 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 // Go 1.1

    // 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 // Go 1.10

    // CertificatePolicies specifies which certificate policy OIDs are
    // acceptable during policy validation. An empty CertificatePolices
    // field implies any valid policy is acceptable.
    CertificatePolicies []OID // Go 1.24
    // contains filtered or unexported fields
}

Поддиректории

Название Краткое описание
..
pkix Пакет pkix содержит общие низкоуровневые структуры, используемые для разбора ASN.1 и сериализации сертификатов X.509, списков отзыва сертификатов (CRL) и OCSP.

© Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
http://golang.org/pkg/crypto/x509/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API