sm2

package
v0.0.0-...-71cb620 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 24, 2020 License: Apache-2.0 Imports: 42 Imported by: 2

Documentation

Overview

Package crypto collects common cryptographic constants.

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

Constants

View Source
const (
	EncryptionAlgorithmDESCBC = iota
	EncryptionAlgorithmAES128GCM
)

Variables

View Source
var ContentEncryptionAlgorithm = EncryptionAlgorithmDESCBC

ContentEncryptionAlgorithm determines the algorithm used to encrypt the plaintext message. Change the value of this variable to change which algorithm is used in the Encrypt() function.

View Source
var ErrNotEncryptedContent = errors.New("pkcs7: content data is a decryptable data type")

ErrNotEncryptedContent is returned when attempting to Decrypt data that is not encrypted data

View Source
var ErrPKCS7UnsupportedAlgorithm = errors.New("pkcs7: cannot decrypt data: only RSA, DES, DES-EDE3, AES-256-CBC and AES-128-GCM supported")

ErrPKCS7UnsupportedAlgorithm tells you when our quick dev assumptions have failed

View Source
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.

View Source
var ErrUnsupportedContentType = errors.New("pkcs7: cannot parse data: unimplemented content type")

ErrUnsupportedContentType is returned when a PKCS7 content is not supported. Currently only Data (1.2.156.10197.6.1.4.2.1), Signed Data (1.2.156.10197.6.1.4.2.2), and Enveloped Data are supported (1.2.156.10197.6.1.4.2.3)

View Source
var ErrUnsupportedEncryptionAlgorithm = errors.New("pkcs7: cannot encrypt content: only DES-CBC and AES-128-GCM supported")

ErrUnsupportedEncryptionAlgorithm is returned when attempting to encrypt content with an unsupported algorithm.

Functions

func BytesCombine

func BytesCombine(pBytes ...[]byte) []byte

func Compress

func Compress(a *PublicKey) []byte

func CreateCertificate

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
  • CRLDistributionPoints
  • DNSNames
  • EmailAddresses
  • ExcludedDNSDomains
  • ExcludedEmailAddresses
  • ExcludedIPRanges
  • ExcludedURIDomains
  • ExtKeyUsage
  • ExtraExtensions
  • IPAddresses
  • IsCA
  • IssuingCertificateURL
  • KeyUsage
  • MaxPathLen
  • MaxPathLenZero
  • NotAfter
  • NotBefore
  • OCSPServer
  • PermittedDNSDomains
  • PermittedDNSDomainsCritical
  • PermittedEmailAddresses
  • PermittedIPRanges
  • PermittedURIDomains
  • PolicyIdentifiers
  • SerialNumber
  • SignatureAlgorithm
  • Subject
  • SubjectKeyId
  • URIs
  • UnknownExtKeyUsage

The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The parameter pub is the public key of the signee and priv is the private key of the signer.

The returned slice is the certificate in DER encoding.

The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. pub must be a supported key type, and priv must be a crypto.Signer with a supported public key.

The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any, unless the resulting certificate is self-signed. Otherwise the value from template will be used.

func CreateCertificateRequest

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:

  • 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 CreateCertificateRequestToMem

func CreateCertificateRequestToMem(template *CertificateRequest, privKey *PrivateKey) ([]byte, error)

func CreateCertificateRequestToPem

func CreateCertificateRequestToPem(FileName string, template *CertificateRequest,
	privKey *PrivateKey) (bool, error)

func CreateCertificateToMem

func CreateCertificateToMem(template, parent *Certificate, pubKey *PublicKey, privKey *PrivateKey) ([]byte, error)

func CreateCertificateToPem

func CreateCertificateToPem(FileName string, template, parent *Certificate, pubKey *PublicKey, privKey *PrivateKey) (bool, error)

func Decrypt

func Decrypt(priv *PrivateKey, data []byte) ([]byte, error)

func DegenerateCertificate

func DegenerateCertificate(cert []byte) ([]byte, error)

DegenerateCertificate creates a signed data structure containing only the provided certificate or certificate chain.

func Encrypt

func Encrypt(pub *PublicKey, data []byte) ([]byte, error)

* sm2密文结构如下: * x * y * hash * CipherText

func KeyExchangeA

func KeyExchangeA(klen int, ida, idb []byte, priA *PrivateKey, pubB *PublicKey, rpri *PrivateKey, rpubB *PublicKey) (k, s1, s2 []byte, err error)

KeyExchangeA 协商第二部,用户A调用,返回共享密钥k

func KeyExchangeB

func KeyExchangeB(klen int, ida, idb []byte, priB *PrivateKey, pubA *PublicKey, rpri *PrivateKey, rpubA *PublicKey) (k, s1, s2 []byte, err error)

KeyExchangeB 协商第二部,用户B调用, 返回共享密钥k

func MarshalPKCS1PrivateKey

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

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

func MarshalPKIXPublicKey

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

MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.

The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey and ed25519.PublicKey. Unsupported key types result in an error.

This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

func MarshalSm2EcryptedPrivateKey

func MarshalSm2EcryptedPrivateKey(PrivKey *PrivateKey, pwd []byte) ([]byte, error)

func MarshalSm2PrivateKey

func MarshalSm2PrivateKey(key *PrivateKey, pwd []byte) ([]byte, error)

func MarshalSm2PublicKey

func MarshalSm2PublicKey(key *PublicKey) ([]byte, error)

func MarshalSm2UnecryptedPrivateKey

func MarshalSm2UnecryptedPrivateKey(key *PrivateKey) ([]byte, error)

func P256Sm2

func P256Sm2() elliptic.Curve

func PKCS7Encrypt

func PKCS7Encrypt(content []byte, recipients []*Certificate) ([]byte, error)

Encrypt creates and returns an envelope data PKCS7 structure with encrypted recipient keys for each recipient public key.

The algorithm used to perform encryption is determined by the current value of the global ContentEncryptionAlgorithm package variable. By default, the value is EncryptionAlgorithmDESCBC. To use a different algorithm, change the value before calling Encrypt(). For example:

ContentEncryptionAlgorithm = EncryptionAlgorithmAES128GCM

TODO(fullsailor): Add support for encrypting content with other algorithms

func ParseCRL

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

ParseCRL parses a CRL from the given bytes. It's often the case that PEM encoded CRLs will appear where they should be DER encoded, so this function will transparently handle PEM encoding as long as there isn't any leading garbage.

func ParseDERCRL

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

ParseDERCRL parses a DER encoded CRL from the given bytes.

func ParsePKCS1PrivateKey

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

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

func ParsePKIXPublicKey

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

ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.

It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or ed25519.PublicKey. More types might be supported in the future.

This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".

func RegisterHash

func RegisterHash(h Hash, f func() hash.Hash)

RegisterHash registers a function that returns a new instance of the given hash function. This is intended to be called from the init function in packages that implement hash functions.

func Sign

func Sign(priv *PrivateKey, hash []byte) (r, s *big.Int, err error)

func SignDataToSignDigit

func SignDataToSignDigit(sign []byte) (*big.Int, *big.Int, error)

func SignDigitToSignData

func SignDigitToSignData(r, s *big.Int) ([]byte, error)

func Sm2Sign

func Sm2Sign(priv *PrivateKey, msg, uid []byte) (r, s *big.Int, err error)

func Sm2Verify

func Sm2Verify(pub *PublicKey, msg, uid []byte, r, s *big.Int) bool

func Verify

func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool

func WNafReversed

func WNafReversed(wnaf []int8) []int8

func WritePrivateKeytoMem

func WritePrivateKeytoMem(key *PrivateKey, pwd []byte) ([]byte, error)

func WritePrivateKeytoPem

func WritePrivateKeytoPem(FileName string, key *PrivateKey, pwd []byte) (bool, error)

func WritePublicKeytoMem

func WritePublicKeytoMem(key *PublicKey, _ []byte) ([]byte, error)

func WritePublicKeytoPem

func WritePublicKeytoPem(FileName string, key *PublicKey, _ []byte) (bool, error)

func ZA

func ZA(pub *PublicKey, uid []byte) ([]byte, error)

ZA = H256(ENTLA || IDA || a || b || xG || yG || xA || yA)

Types

type Attribute

type Attribute struct {
	Type  asn1.ObjectIdentifier
	Value interface{}
}

Attribute represents a key value pair attribute. Value must be marshalable byte `encoding/asn1`

type CertPool

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

CertPool is a set of certificates.

func NewCertPool

func NewCertPool() *CertPool

NewCertPool returns a new, empty CertPool.

func SystemCertPool

func SystemCertPool() (*CertPool, error)

SystemCertPool returns a copy of the system cert pool.

Any mutations to the returned pool are not written to disk and do not affect any other pool returned by SystemCertPool.

New changes in the system cert pool might not be reflected in subsequent calls.

func (*CertPool) AddCert

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

AddCert adds a certificate to a pool.

func (*CertPool) AppendCertsFromPEM

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

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

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

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

	PublicKeyAlgorithm PublicKeyAlgorithm
	PublicKey          interface{}

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

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

	// ExtraExtensions contains extensions to be copied, raw, into any
	// marshaled certificates. Values override any extensions that would
	// otherwise be produced based on the other fields. The ExtraExtensions
	// field is not populated when parsing certificates, see Extensions.
	ExtraExtensions []pkix.Extension

	// UnhandledCriticalExtensions contains a list of extension IDs that
	// were not (fully) processed when parsing. Verify will fail if this
	// slice is non-empty, unless verification is delegated to an OS
	// library which understands all the critical extensions.
	//
	// Users can access these extensions using Extensions and can remove
	// elements from this slice if they believe that they have been
	// handled.
	UnhandledCriticalExtensions []asn1.ObjectIdentifier

	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.

	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
	// and MaxPathLenZero are valid.
	BasicConstraintsValid bool
	IsCA                  bool

	// MaxPathLen and MaxPathLenZero indicate the presence and
	// value of the BasicConstraints' "pathLenConstraint".
	//
	// When parsing a certificate, a positive non-zero MaxPathLen
	// means that the field was specified, -1 means it was unset,
	// and MaxPathLenZero being true mean that the field was
	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
	// should be treated equivalent to -1 (unset).
	//
	// When generating a certificate, an unset pathLenConstraint
	// can be requested with either MaxPathLen == -1 or using the
	// zero value for both MaxPathLen and MaxPathLenZero.
	MaxPathLen int
	// MaxPathLenZero indicates that BasicConstraintsValid==true
	// and MaxPathLen==0 should be interpreted as an actual
	// maximum path length of zero. Otherwise, that combination is
	// interpreted as MaxPathLen not being set.
	MaxPathLenZero bool

	SubjectKeyId   []byte
	AuthorityKeyId []byte

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

	// Subject Alternate Name values. (Note that these values may not be valid
	// if invalid values were contained within a parsed certificate. For
	// example, an element of DNSNames may not be a valid DNS domain name.)
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL

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

	// CRL Distribution Points
	CRLDistributionPoints []string

	PolicyIdentifiers []asn1.ObjectIdentifier
}

A Certificate represents an X.509 certificate.

func ParseCertificate

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

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

func ParseCertificates

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 ReadCertificateFromMem

func ReadCertificateFromMem(data []byte) (*Certificate, error)

func ReadCertificateFromPem

func ReadCertificateFromPem(FileName string) (*Certificate, error)

func (*Certificate) CheckCRLSignature

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

CheckCRLSignature checks that the signature in crl is from c.

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.

func (*Certificate) CheckSignatureFrom

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

func (*Certificate) CreateCRL

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

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

func (*Certificate) Verify

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.

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.

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 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          interface{}

	Subject pkix.Name

	// Attributes contains the CSR attributes that can parse as
	// pkix.AttributeTypeAndValueSET.
	//
	// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
	// generating the requestedExtensions attribute.
	Attributes []pkix.AttributeTypeAndValueSET

	// Extensions contains all requested extensions, in raw form. When parsing
	// CSRs, this can be used to extract extensions that are not parsed by this
	// package.
	Extensions []pkix.Extension

	// ExtraExtensions contains extensions to be copied, raw, into any CSR
	// marshaled by CreateCertificateRequest. Values override any extensions
	// that would otherwise be produced based on the other fields but are
	// overridden by any extensions specified in Attributes.
	//
	// The ExtraExtensions field is not populated by ParseCertificateRequest,
	// see Extensions instead.
	ExtraExtensions []pkix.Extension

	// Subject Alternate Name values.
	DNSNames       []string
	EmailAddresses []string
	IPAddresses    []net.IP
	URIs           []*url.URL
}

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 ReadCertificateRequestFromMem

func ReadCertificateRequestFromMem(data []byte) (*CertificateRequest, error)

func ReadCertificateRequestFromPem

func ReadCertificateRequestFromPem(FileName string) (*CertificateRequest, error)

func (*CertificateRequest) CheckSignature

func (c *CertificateRequest) CheckSignature() error

CheckSignature reports whether the signature on c is valid.

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

type Decrypter

type Decrypter interface {
	// Public returns the public key corresponding to the opaque,
	// private key.
	Public() PublicKey

	// Decrypt decrypts msg. The opts argument should be appropriate for
	// the primitive used. See the documentation in each implementation for
	// details.
	Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
}

Decrypter is an interface for an opaque private key that can be used for asymmetric decryption operations. An example would be an RSA key kept in a hardware module.

type DecrypterOpts

type DecrypterOpts interface{}

type EncryptedPrivateKeyInfo

type EncryptedPrivateKeyInfo struct {
	EncryptionAlgorithm Pbes2Algorithms
	EncryptedData       []byte
}

reference to https://www.rfc-editor.org/rfc/rfc5958.txt

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 (
	ExtKeyUsageAny ExtKeyUsage = iota
	ExtKeyUsageServerAuth
	ExtKeyUsageClientAuth
	ExtKeyUsageCodeSigning
	ExtKeyUsageEmailProtection
	ExtKeyUsageIPSECEndSystem
	ExtKeyUsageIPSECTunnel
	ExtKeyUsageIPSECUser
	ExtKeyUsageTimeStamping
	ExtKeyUsageOCSPSigning
	ExtKeyUsageMicrosoftServerGatedCrypto
	ExtKeyUsageNetscapeServerGatedCrypto
	ExtKeyUsageMicrosoftCommercialCodeSigning
	ExtKeyUsageMicrosoftKernelCodeSigning
)

type Hash

type Hash uint

Hash identifies a cryptographic hash function that is implemented in another package.

const (
	MD4         Hash = 1 + iota // import golang.org/x/crypto/md4
	MD5                         // import crypto/md5
	SHA1                        // import crypto/sha1
	SHA224                      // import crypto/sha256
	SHA256                      // import crypto/sha256
	SHA384                      // import crypto/sha512
	SHA512                      // import crypto/sha512
	MD5SHA1                     // no implementation; MD5+SHA1 used for TLS RSA
	RIPEMD160                   // import golang.org/x/crypto/ripemd160
	SHA3_224                    // import golang.org/x/crypto/sha3
	SHA3_256                    // import golang.org/x/crypto/sha3
	SHA3_384                    // import golang.org/x/crypto/sha3
	SHA3_512                    // import golang.org/x/crypto/sha3
	SHA512_224                  // import crypto/sha512
	SHA512_256                  // import crypto/sha512
	BLAKE2s_256                 // import golang.org/x/crypto/blake2s
	BLAKE2b_256                 // import golang.org/x/crypto/blake2b
	BLAKE2b_384                 // import golang.org/x/crypto/blake2b
	BLAKE2b_512                 // import golang.org/x/crypto/blake2b
	SM3
)

func (Hash) Available

func (h Hash) Available() bool

Available reports whether the given hash function is linked into the binary.

func (Hash) HashFunc

func (h Hash) HashFunc() Hash

HashFunc simply returns the value of h so that Hash implements SignerOpts.

func (Hash) New

func (h Hash) New() hash.Hash

New returns a new hash.Hash calculating the given hash function. New panics if the hash function is not linked into the binary.

func (Hash) Size

func (h Hash) Size() int

Size returns the length, in bytes, of a digest resulting from the given hash function. It doesn't require that the hash function in question be linked into the program.

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

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
	// TooManyIntermediates results when a path length constraint is
	// violated.
	TooManyIntermediates
	// IncompatibleUsage results when the certificate's key usage indicates
	// that it may only be used for a different purpose.
	IncompatibleUsage
	// NameMismatch results when the subject name of a parent certificate
	// does not match the issuer name in the child.
	NameMismatch
	// NameConstraintsWithoutSANs results when a leaf certificate doesn't
	// contain a Subject Alternative Name extension, but a CA certificate
	// contains name constraints, and the Common Name can be interpreted as
	// a hostname.
	//
	// You can avoid this error by setting the experimental GODEBUG environment
	// variable to "x509ignoreCN=1", disabling Common Name matching entirely.
	// This behavior might become the default in the future.
	NameConstraintsWithoutSANs
	// UnconstrainedName results when a CA certificate contains permitted
	// name constraints, but leaf certificate contains a name of an
	// unsupported or unconstrained type.
	UnconstrainedName
	// TooManyConstraints results when the number of comparison operations
	// needed to check a certificate exceeds the limit set by
	// VerifyOptions.MaxConstraintComparisions. This limit exists to
	// prevent pathological certificates can consuming excessive amounts of
	// CPU time to verify.
	TooManyConstraints
	// CANotAuthorizedForExtKeyUsage results when an intermediate or root
	// certificate does not permit a requested extended key usage.
	CANotAuthorizedForExtKeyUsage
)

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.

const (
	KeyUsageDigitalSignature KeyUsage = 1 << iota
	KeyUsageContentCommitment
	KeyUsageKeyEncipherment
	KeyUsageDataEncipherment
	KeyUsageKeyAgreement
	KeyUsageCertSign
	KeyUsageCRLSign
	KeyUsageEncipherOnly
	KeyUsageDecipherOnly
)

type MessageDigestMismatchError

type MessageDigestMismatchError struct {
	ExpectedDigest []byte
	ActualDigest   []byte
}

MessageDigestMismatchError is returned when the signer data digest does not match the computed digest for the contained content

func (*MessageDigestMismatchError) Error

func (err *MessageDigestMismatchError) Error() string

type PKCS7

type PKCS7 struct {
	Content      []byte
	Certificates []*Certificate
	CRLs         []pkix.CertificateList
	Signers      []signerInfo
	// contains filtered or unexported fields
}

PKCS7 Represents a PKCS7 structure

func ParsePKCS7

func ParsePKCS7(data []byte) (p7 *PKCS7, err error)

ParsePKCS7 decodes a DER encoded PKCS7.

func (*PKCS7) Decrypt

func (p7 *PKCS7) Decrypt(cert *Certificate, pk crypto.PrivateKey) ([]byte, error)

Decrypt decrypts encrypted content info for recipient cert and private key

func (*PKCS7) GetOnlySigner

func (p7 *PKCS7) GetOnlySigner() *Certificate

GetOnlySigner returns an x509.Certificate for the first signer of the signed data payload. If there are more or less than one signer, nil is returned

func (*PKCS7) UnmarshalSignedAttribute

func (p7 *PKCS7) UnmarshalSignedAttribute(attributeType asn1.ObjectIdentifier, out interface{}) error

UnmarshalSignedAttribute decodes a single attribute from the signer info

func (*PKCS7) Verify

func (p7 *PKCS7) Verify() (err error)

Verify checks the signatures of a PKCS7 object WARNING: Verify does not check signing time or verify certificate chains at this time.

type Pbes2Algorithms

type Pbes2Algorithms struct {
	IdPBES2     asn1.ObjectIdentifier
	Pbes2Params Pbes2Params
}

reference to https://www.ietf.org/rfc/rfc2898.txt

type Pbes2Encs

type Pbes2Encs struct {
	EncryAlgo asn1.ObjectIdentifier
	IV        []byte
}

type Pbes2KDfs

type Pbes2KDfs struct {
	IdPBKDF2    asn1.ObjectIdentifier
	Pkdf2Params Pkdf2Params
}

reference to https://www.ietf.org/rfc/rfc2898.txt

type Pbes2Params

type Pbes2Params struct {
	KeyDerivationFunc Pbes2KDfs // PBES2-KDFs
	EncryptionScheme  Pbes2Encs // PBES2-Encs
}

reference to https://www.ietf.org/rfc/rfc2898.txt

type Pkdf2Params

type Pkdf2Params struct {
	Salt           []byte
	IterationCount int
	Prf            pkix.AlgorithmIdentifier
}

reference to https://www.ietf.org/rfc/rfc2898.txt

type PrivateKey

type PrivateKey struct {
	PublicKey
	D *big.Int
}

func GenerateKey

func GenerateKey() (*PrivateKey, error)

func ParsePKCS8EcryptedPrivateKey

func ParsePKCS8EcryptedPrivateKey(der, pwd []byte) (*PrivateKey, error)

func ParsePKCS8PrivateKey

func ParsePKCS8PrivateKey(der, pwd []byte) (*PrivateKey, error)

func ParsePKCS8UnecryptedPrivateKey

func ParsePKCS8UnecryptedPrivateKey(der []byte) (*PrivateKey, error)

func ParseSm2PrivateKey

func ParseSm2PrivateKey(der []byte) (*PrivateKey, error)

func ReadPrivateKeyFromMem

func ReadPrivateKeyFromMem(data []byte, pwd []byte) (*PrivateKey, error)

func ReadPrivateKeyFromPem

func ReadPrivateKeyFromPem(FileName string, pwd []byte) (*PrivateKey, error)

func (*PrivateKey) Decrypt

func (priv *PrivateKey) Decrypt(rand io.Reader, msg []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)

func (*PrivateKey) DecryptSrc

func (priv *PrivateKey) DecryptSrc(data []byte) ([]byte, error)

func (*PrivateKey) Public

func (priv *PrivateKey) Public() crypto.PublicKey

The SM2's private key contains the public key

func (*PrivateKey) Sign

func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)

sign format = 30 + len(z) + 02 + len(r) + r + 02 + len(s) + s, z being what follows its size, ie 02+len(r)+r+02+len(s)+s

type PrivateKeyInfo

type PrivateKeyInfo struct {
	Version             int // v1 or v2
	PrivateKeyAlgorithm []asn1.ObjectIdentifier
	PrivateKey          []byte
}

reference to https://www.rfc-editor.org/rfc/rfc5958.txt

type PublicKey

type PublicKey struct {
	elliptic.Curve
	X, Y *big.Int
}

func Decompress

func Decompress(a []byte) *PublicKey

func ParseSm2PublicKey

func ParseSm2PublicKey(der []byte) (*PublicKey, error)

func ReadPublicKeyFromMem

func ReadPublicKeyFromMem(data []byte, _ []byte) (*PublicKey, error)

func ReadPublicKeyFromPem

func ReadPublicKeyFromPem(FileName string, pwd []byte) (*PublicKey, error)

func (*PublicKey) Encrypt

func (pub *PublicKey) Encrypt(data []byte) ([]byte, error)

func (*PublicKey) Verify

func (pub *PublicKey) Verify(msg []byte, sign []byte) bool

type PublicKeyAlgorithm

type PublicKeyAlgorithm int
const (
	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
	RSA
	DSA
	ECDSA
	Ed25519
)

func (PublicKeyAlgorithm) String

func (algo PublicKeyAlgorithm) String() string

type SignatureAlgorithm

type SignatureAlgorithm int
const (
	UnknownSignatureAlgorithm SignatureAlgorithm = iota
	MD2WithRSA
	MD5WithRSA
	SHA1WithRSA
	SHA256WithRSA
	SHA384WithRSA
	SHA512WithRSA
	DSAWithSHA1
	DSAWithSHA256
	ECDSAWithSHA1
	ECDSAWithSHA256
	ECDSAWithSHA384
	ECDSAWithSHA512
	SHA256WithRSAPSS
	SHA384WithRSAPSS
	SHA512WithRSAPSS
	PureEd25519
	SM2WithSM3
	SM2WithSHA1
	SM2WithSHA256
)

func (SignatureAlgorithm) String

func (algo SignatureAlgorithm) String() string

type SignedData

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

SignedData is an opaque data structure for creating signed data payloads

func NewSignedData

func NewSignedData(data []byte) (*SignedData, error)

NewSignedData initializes a SignedData with content

func (*SignedData) AddCertificate

func (sd *SignedData) AddCertificate(cert *Certificate)

AddCertificate adds the certificate to the payload. Useful for parent certificates

func (*SignedData) AddSigner

func (sd *SignedData) AddSigner(cert *Certificate, pkey crypto.PrivateKey, config SignerInfoConfig) error

AddSigner signs attributes about the content and adds certificate to payload

func (*SignedData) Detach

func (sd *SignedData) Detach()

Detach removes content from the signed data struct to make it a detached signature. This must be called right before Finish()

func (*SignedData) Finish

func (sd *SignedData) Finish() ([]byte, error)

Finish marshals the content and its signers

type Signer

type Signer interface {
	// Public returns the public key corresponding to the opaque,
	// private key.
	Public() PublicKey

	// Sign signs digest with the private key, possibly using entropy from
	// rand. For an RSA key, the resulting signature should be either a
	// PKCS#1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
	// key, it should be a DER-serialised, ASN.1 signature structure.
	//
	// Hash implements the SignerOpts interface and, in most cases, one can
	// simply pass in the hash function used as opts. Sign may also attempt
	// to type assert opts to other types in order to obtain algorithm
	// specific values. See the documentation in each package for details.
	//
	// Note that when a signature of a hash of a larger message is needed,
	// the caller is responsible for hashing the larger message and passing
	// the hash (as digest) and the hash function (as opts) to Sign.
	Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
}

Signer is an interface for an opaque private key that can be used for signing operations. For example, an RSA key kept in a hardware module.

type SignerInfoConfig

type SignerInfoConfig struct {
	ExtraSignedAttributes []Attribute
}

SignerInfoConfig are optional values to include when adding a signer

type SignerOpts

type SignerOpts interface {
	// HashFunc returns an identifier for the hash function used to produce
	// the message passed to Signer.Sign, or else zero to indicate that no
	// hashing was done.
	HashFunc() Hash
}

SignerOpts contains options for signing with a Signer.

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

type UnhandledCriticalExtension

type UnhandledCriticalExtension struct{}

func (UnhandledCriticalExtension) Error

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 VerifyOptions

type VerifyOptions struct {
	DNSName       string
	Intermediates *CertPool
	Roots         *CertPool // if nil, the system roots are used
	CurrentTime   time.Time // if zero, the current time is used
	// KeyUsage specifies which Extended Key Usage values are acceptable. A leaf
	// certificate is accepted if it contains any of the listed values. An empty
	// list means ExtKeyUsageServerAuth. To accept any key usage, include
	// ExtKeyUsageAny.
	//
	// Certificate chains are required to nest these extended key usage values.
	// (This matches the Windows CryptoAPI behavior, but not the spec.)
	KeyUsages []ExtKeyUsage
	// MaxConstraintComparisions is the maximum number of comparisons to
	// perform when checking a given certificate's name constraints. If
	// zero, a sensible default is used. This limit prevents pathological
	// certificates from consuming excessive amounts of CPU time when
	// validating.
	MaxConstraintComparisions int
}

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL