csp

package
v2.0.0-...-f88f6b9 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package csp provides mid-level cryptographic API based on CryptoAPI 2.0 on Windows and CryptoPro CSP on Linux.

Index

Constants

View Source
const (
	// RevocationCheckNone skips revocation entirely: the chain is only built
	// and its signatures, validity dates and trust anchor are evaluated.
	RevocationCheckNone uint32 = 0
	// RevocationCheckEndCert checks revocation of the end certificate only.
	RevocationCheckEndCert uint32 = 0x10000000
	// RevocationCheckChain checks revocation for every certificate in the chain.
	RevocationCheckChain uint32 = 0x20000000
	// RevocationCheckChainExcludeRoot checks revocation for the whole chain
	// except the self-signed root. This is the closest equivalent of what
	// `cryptcp -verify -errchain` does and is the recommended default.
	RevocationCheckChainExcludeRoot uint32 = 0x40000000
	// RevocationCheckCacheOnly forbids network retrieval: revocation is
	// resolved from the local cache and stores only. Combine with one of the
	// modes above. Without a populated cache this yields
	// TrustRevocationStatusUnknown rather than an error.
	RevocationCheckCacheOnly uint32 = 0x80000000
)

Revocation checking modes for BuildChain. They mirror the CERT_CHAIN_REVOCATION_CHECK_* flags from <wincrypt.h>.

View Source
const (
	TrustIsNotTimeValid          uint32 = 0x00000001
	TrustIsRevoked               uint32 = 0x00000004
	TrustIsNotSignatureValid     uint32 = 0x00000008
	TrustIsNotValidForUsage      uint32 = 0x00000010
	TrustIsUntrustedRoot         uint32 = 0x00000020
	TrustRevocationStatusUnknown uint32 = 0x00000040
	TrustIsCyclic                uint32 = 0x00000080
	TrustIsPartialChain          uint32 = 0x00010000
	TrustCtlIsNotTimeValid       uint32 = 0x00020000
	TrustCtlIsNotSignatureValid  uint32 = 0x00040000
	TrustCtlIsNotValidForUsage   uint32 = 0x00080000
	TrustIsOfflineRevocation     uint32 = 0x01000000
	TrustNoIssuanceChainPolicy   uint32 = 0x02000000
)

CERT_TRUST_* error bits reported through ChainStatus.

View Source
const (
	GOSTR341012256 = "1.2.643.7.1.1.1.1"
	GOSTR341012512 = "1.2.643.7.1.1.1.2"
)

Public key algorithm IDs

Variables

View Source
var (
	// ErrEmptyInput is returned when data or signature is empty.
	ErrEmptyInput = errors.New("csp: empty data or signature")
	// ErrNoSigners is returned when the CMS message carries no SignerInfo.
	ErrNoSigners = errors.New("csp: message contains no signers")
)

Errors returned by VerifyDetachedCMS when verification cannot be carried out at all, as opposed to completing with a negative verdict.

View Source
var (
	GOST_R3411        asn1.ObjectIdentifier = []int{1, 2, 643, 2, 2, 9}
	GOST_R3411_12_256 asn1.ObjectIdentifier = []int{1, 2, 643, 7, 1, 1, 2, 2}
	GOST_R3411_12_512 asn1.ObjectIdentifier = []int{1, 2, 643, 7, 1, 1, 2, 3}

	MD5RSA      asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 1, 4}
	SHA1RSA     asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 1, 5}
	SETOAEP_RSA asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 1, 6}

	SHA256RSA asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 1, 11}
	SHA384RSA asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 1, 12}
	SHA512RSA asn1.ObjectIdentifier = []int{1, 2, 840, 113549, 1, 1, 13}
)

Common object identifiers

View Source
var ErrZeroCertificate = errors.New("csp: zero certificate")

ErrZeroCertificate is returned when BuildChain is given a zero Cert.

Functions

func BlockDecrypt

func BlockDecrypt(recipient Cert, data BlockEncryptedData) ([]byte, error)

func Container

func Container(cont string) string

Container returns HDIMAGE container name for CryptoPro linux CSP

func DecryptData

func DecryptData(data []byte, store *CertStore) ([]byte, error)

DecryptData decrypts byte slice using provided certificate store for private key lookup

func DeleteCtx

func DeleteCtx(container, provider string, provType ProvType) error

DeleteCtx deletes key container from CSP.

func EncryptData

func EncryptData(data []byte, options EncryptOptions) (_ []byte, rErr error)

EncryptData encrypts arbitrary byte slice for one or more recipient certificates

Types

type AlgorithmIdentifier

type AlgorithmIdentifier struct {
	PublicKeyOID asn1.ObjectIdentifier
	SignParams   SignParams
}

type BlockEncryptOptions

type BlockEncryptOptions struct {
	Receiver Cert
	KeyAlg   C.ALG_ID // If not set, C.CALG_DH_GR3410_12_256_EPHEM is used
	KeyExp   C.DWORD  // If not set, C.CALG_PRO_EXPORT is used
}

type BlockEncryptedData

type BlockEncryptedData struct {
	IV               []byte
	CipherText       []byte
	SessionKey       SessionKey
	SessionPublicKey []byte
	KeyExp           C.DWORD
	DHParamsOID      string
	DigestOID        string
	PublicKeyOID     string
}

func BlockEncrypt

func BlockEncrypt(opts BlockEncryptOptions, data []byte) (BlockEncryptedData, error)

func (BlockEncryptedData) ToGOST2001KeyTransport

func (s BlockEncryptedData) ToGOST2001KeyTransport() []byte

func (BlockEncryptedData) ToGOST2001KeyTransportASN1

func (s BlockEncryptedData) ToGOST2001KeyTransportASN1() (res Gost2001KeyTransportASN1, _ error)

type CMSVerification

type CMSVerification struct {
	Signers []SignerVerification
}

CMSVerification aggregates the per-signer outcomes of a CMS verification.

func VerifyDetachedCMS

func VerifyDetachedCMS(data, sig []byte, opts ...CMSVerifyOption) (*CMSVerification, error)

VerifyDetachedCMS verifies a detached PKCS#7/CMS signature over data.

Every SignerInfo in the message is checked: the signature itself against the signer certificate, then that certificate's chain up to a trusted root in the system stores, including revocation. Chain evaluation goes through the default chain engine, which caches built chains and fetched CRLs for the lifetime of the process — repeat verifications against the same CA are therefore cheap.

A non-nil error means verification could not be performed: malformed input, an unreadable message, or a failure inside CryptoAPI. A nil error means the message was examined and the verdict is in the result — check OK().

func (CMSVerification) OK

func (v CMSVerification) OK() bool

OK reports whether every signer in the message passed every check. A message with no signers is never OK.

Requiring all signers to be valid matches what `cryptcp -verify` does: it fails if any signature in the file is bad.

func (CMSVerification) Reason

func (v CMSVerification) Reason() string

Reason returns a description of every signer that failed, or an empty string when the message is fully valid.

type CMSVerifyOption

type CMSVerifyOption func(*cmsVerifyConfig)

CMSVerifyOption configures VerifyDetachedCMS.

func WithRevocationMode

func WithRevocationMode(flags uint32) CMSVerifyOption

WithRevocationMode selects how revocation is checked while evaluating the signer's certificate chain. Pass one of the RevocationCheck* constants, optionally combined with RevocationCheckCacheOnly.

The default is RevocationCheckChainExcludeRoot, which mirrors `cryptcp -verify -errchain`.

func WithSignerNames

func WithSignerNames() CMSVerifyOption

WithSignerNames makes VerifyDetachedCMS populate Subject and Issuer on every SignerVerification. Off by default: rendering X.509 names costs a little and most callers only need the verdict.

func WithoutRevocation

func WithoutRevocation() CMSVerifyOption

WithoutRevocation skips revocation checking entirely. The chain is still built and its trust anchor, validity dates and signatures are evaluated.

type Cert

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

Cert encapsulates certificate context

func ParseCert

func ParseCert(buf []byte) (res Cert, err error)

ParseCert creates certificate context from byte slice

func (Cert) Bytes

func (c Cert) Bytes() []byte

Bytes returns encoded certificate as byte slice

func (Cert) Close

func (c Cert) Close() error

Close releases certificate context

func (Cert) Context

func (c Cert) Context() (Ctx, error)

Context returns cryptographic context associated with the certificate

func (Cert) GetProperty

func (c Cert) GetProperty(propID CertPropertyID) ([]byte, error)

GetProperty is a base function for extracting certificate context properties

func (Cert) Info

func (c Cert) Info() CertInfo

Info extracts CertInfo from Cert

func (Cert) IsZero

func (c Cert) IsZero() bool

IsZero returns true if certificate struct was not initialized

func (Cert) MustSubjectID

func (c Cert) MustSubjectID() string

MustSubjectID returns certificate's subject id or panics

func (Cert) MustThumbPrint

func (c Cert) MustThumbPrint() string

MustThumbPrint returns certificate's hash as a hexadecimal string or panics

func (Cert) Serial

func (c Cert) Serial() string

Serial returns the certificate's serial number as a big-endian hex string. CryptoAPI stores SerialNumber as little-endian in CRYPT_INTEGER_BLOB; we reverse it for the conventional big-endian display order.

func (Cert) SubjectID

func (c Cert) SubjectID() (string, error)

SubjectID returns certificate's subject public key ID as a hexadecimal string

func (Cert) ThumbPrint

func (c Cert) ThumbPrint() (string, error)

ThumbPrint returns certificate's hash as a hexadecimal string

type CertInfo

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

CertInfo encapsulates certificate properties

func (CertInfo) IssuerStr

func (ci CertInfo) IssuerStr() (string, error)

IssuerStr returns certificate issuer converted to Go string

func (CertInfo) PublicKeyAlgorithm

func (ci CertInfo) PublicKeyAlgorithm() string

PublicKeyAlgorithm returns certificate subject public key algorithm as object ID string

func (CertInfo) PublicKeyBytes

func (ci CertInfo) PublicKeyBytes() []byte

PublicKeyBytes returns certificate subject public key as byte slice

func (CertInfo) SignatureAlgorithm

func (ci CertInfo) SignatureAlgorithm() string

SignatureAlgorithm returns certificate signature algorithm as object ID string

func (CertInfo) SubjectStr

func (ci CertInfo) SubjectStr() (string, error)

SubjectStr returns certificate subject converted to Go string

type CertPropertyID

type CertPropertyID C.DWORD

CertPropertyID corresponds to a C type of DWORD

const (
	CertHashProp          CertPropertyID = C.CERT_HASH_PROP_ID
	CertKeyIDentifierProp CertPropertyID = C.CERT_KEY_IDENTIFIER_PROP_ID
	CertProvInfoProp      CertPropertyID = C.CERT_KEY_PROV_INFO_PROP_ID
)

Constants for certificate property IDs

type CertStore

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

CertStore incapsulates certificate store

func MemoryStore

func MemoryStore() (res CertStore, err error)

MemoryStore returns handle to new empty in-memory certificate store

func SystemStore

func SystemStore(name string) (*CertStore, error)

SystemStore returns handle to certificate store with certain name, using default system cryptoprovider

func (CertStore) Add

func (s CertStore) Add(cert Cert) error

Add inserts certificate into store replacing existing certificate link if it's already added

func (CertStore) Certs

func (s CertStore) Certs() (res []Cert)

func (CertStore) Close

func (s CertStore) Close() error

Close releases cert store handle

func (CertStore) FindBySubject

func (s CertStore) FindBySubject(subject string) []Cert

FindBySubject returns slice of certificates with a subject that matches string

func (CertStore) FindBySubjectId

func (s CertStore) FindBySubjectId(thumb string) []Cert

FindBySubjectId returns slice of certificates that match given subject key ID. If ID supplied could not be decoded from string, FindBySubjectId will return nil slice

func (CertStore) FindByThumb

func (s CertStore) FindByThumb(thumb string) []Cert

FindByThumb returns slice of certificates that match given thumbprint. If thumbprint supplied could not be decoded from string, FindByThumb will return nil slice

func (CertStore) GetByID

func (s CertStore) GetByID(issuerName []byte, serialNumber *big.Int) (res Cert, err error)

GetByID returns certificate with specified issuer and serial number

func (CertStore) GetBySubject

func (s CertStore) GetBySubject(subject string) (res Cert, err error)

GetBySubject returns first certificate with a subject that matches given string

func (CertStore) GetBySubjectId

func (s CertStore) GetBySubjectId(keyId string) (res Cert, err error)

GetBySubjectId returns first certificate in store that match given subject key ID

func (CertStore) GetByThumb

func (s CertStore) GetByThumb(thumb string) (res Cert, err error)

GetByThumb returns first certificate in store that match given thumbprint

type ChainStatus

type ChainStatus uint32

ChainStatus is the raw CERT_TRUST_STATUS.dwErrorStatus bitmask produced by chain evaluation. Zero means the chain is fully trusted.

func BuildChain

func BuildChain(cert Cert, extra *CertStore, flags uint32) (ChainStatus, error)

BuildChain builds and evaluates the certificate chain for cert using the default chain engine, which caches built chains and fetched CRLs for the lifetime of the process.

extra supplies additional intermediate certificates and may be nil. When verifying a detached CMS signature, pass the message certificate store obtained from Msg.CertStore(); the issuer of the signer certificate is normally carried inside the message rather than installed system-wide.

flags selects the revocation mode — see the RevocationCheck* constants. RevocationCheckChainExcludeRoot is the usual choice.

A non-nil error means chain evaluation could not be performed at all. A nil error with a non-zero ChainStatus means the chain was evaluated and found wanting; inspect the status bits to tell "expired" from "revoked" from "untrusted root".

func (ChainStatus) Has

func (s ChainStatus) Has(bit uint32) bool

Has reports whether a specific CERT_TRUST_* bit is set.

func (ChainStatus) OK

func (s ChainStatus) OK() bool

OK reports whether chain evaluation raised no complaints at all.

func (ChainStatus) Problems

func (s ChainStatus) Problems() []string

Problems returns the symbolic names of every error bit that is set.

func (ChainStatus) String

func (s ChainStatus) String() string

type CryptFlag

type CryptFlag C.DWORD

CryptFlag determines behaviour of acquired context

const (
	CryptVerifyContext CryptFlag = C.CRYPT_VERIFYCONTEXT
	CryptNewKeyset     CryptFlag = C.CRYPT_NEWKEYSET
	CryptMachineKeyset CryptFlag = C.CRYPT_MACHINE_KEYSET
	CryptDeleteKeyset  CryptFlag = C.CRYPT_DELETEKEYSET
	CryptSilent        CryptFlag = C.CRYPT_SILENT
)

Flags for acquiring context

type CryptoProvider

type CryptoProvider struct {
	Name string
	Type ProvType
}

CryptoProvider struct contains description of CSP that can be used for creation of CSP Context.

func EnumProviders

func EnumProviders() (res []CryptoProvider, err error)

EnumProviders returns slice of CryptoProvider structures, describing available CSPs.

type Ctx

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

Ctx is a CSP context nessessary for cryptographic functions.

func AcquireCtx

func AcquireCtx(container, provider string, provType ProvType, flags CryptFlag) (res Ctx, err error)

AcquireCtx acquires new CSP context from container name, provider name, type and flags. Empty strings for container and provider names are typically used for CryptVerifyContext flag setting. Created context must be eventually released with its Close method.

func (Ctx) CertStore

func (c Ctx) CertStore(name string) (res CertStore, err error)

CertStore method returns handle to certificate store in certain CSP context

func (Ctx) Close

func (ctx Ctx) Close() error

Close releases CSP context

func (Ctx) GenKey

func (ctx Ctx) GenKey(at KeyPairID, flags KeyFlag) (res Key, err error)

GenKey generates public/private key pair for given context. Flags parameter determines if generated key will be exportable or archivable and at parameter determines KeyExchange or Signature key pair. Resulting key must be eventually closed by calling Close.

func (Ctx) ImportKey

func (ctx Ctx) ImportKey(buf SimpleBlob, cryptKey *Key) (Key, error)

ImportKey transfers a cryptographic key from a key BLOB into a context.

func (Ctx) ImportPublicKeyInfo

func (ctx Ctx) ImportPublicKeyInfo(cert Cert) (Key, error)

ImportPublicKeyInfo imports public key information into the context and returns public key

func (Ctx) IsZero

func (c Ctx) IsZero() bool

IsZero returns true if context was not initialized

func (Ctx) Key

func (ctx Ctx) Key(at KeyPairID) (res Key, err error)

Key extracts public key from container represented by context ctx, from key pair given by at parameter. It must be released after use by calling Close method.

func (Ctx) SetDHOID

func (ctx Ctx) SetDHOID(oid string) error

SetDHOID changes D-H OID on key container to specified OID (typically, result of Key.GetDHOID method)

func (Ctx) SetPassword

func (ctx Ctx) SetPassword(pwd string, at KeyPairID) error

SetPassword changes PIN on key container acquired with AcquireCtx to pwd. Which private/public key pair affected is determined by at parameter.

type Decryptor

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

func OpenToDecrypt

func OpenToDecrypt(dest io.Writer, store *CertStore, maxHeaderSize int) (msg *Decryptor, rErr error)

OpenToDecrypt creates new Msg in decrypt mode. Maximum header size, if non-zero, limits size of data read from message until envelope recipient info is available.

func (*Decryptor) Write

func (msg *Decryptor) Write(buf []byte) (int, error)

Write encodes provided bytes into message output data stream

type EncodeOptions

type EncodeOptions struct {
	Detached bool                  // Signature is detached
	HashAlg  asn1.ObjectIdentifier // Signature hash algorithm ID
	Signers  []Cert                // Signing certificate list
}

EncodeOptions specifies message creation details

type EncryptOID

type EncryptOID string

type EncryptOptions

type EncryptOptions struct {
	Receivers  []Cert // Receiving certificate list
	EncryptOID EncryptOID
}

EncryptOptions specifies message encryption details

type Error

type Error struct {
	Code ErrorCode // Code indicates exact CryptoAPI error code
	// contains filtered or unexported fields
}

Error provides error type

func (Error) Error

func (e Error) Error() string

type ErrorCode

type ErrorCode C.DWORD

ErrorCode corresponds to a C type DWORD

const (
	ErrBadKeysetParam ErrorCode = C.NTE_BAD_KEYSET_PARAM & (1<<32 - 1) // Typically occurs when trying to acquire context
	ErrFail           ErrorCode = C.NTE_FAIL & (1<<32 - 1)             // Misc error
	// ErrInvalidParameter ErrorCode = C.NTE_INVALID_PARAMETER & (1<<32 - 1) // Bad parameter to cryptographic function
	ErrNoKey          ErrorCode = C.NTE_NO_KEY & (1<<32 - 1)                   // Key not found
	ErrExists         ErrorCode = C.NTE_EXISTS & (1<<32 - 1)                   // Object already exists
	ErrNotFound       ErrorCode = C.NTE_NOT_FOUND & (1<<32 - 1)                // Object not found
	ErrKeysetNotDef   ErrorCode = C.NTE_KEYSET_NOT_DEF & (1<<32 - 1)           // Operation on unknown container
	ErrBadKeyset      ErrorCode = C.NTE_BAD_KEYSET & (1<<32 - 1)               // Operation on unknown container
	ErrStreamNotReady ErrorCode = C.CRYPT_E_STREAM_MSG_NOT_READY & (1<<32 - 1) // Returned until stream header is parsed
	ErrCryptNotFound  ErrorCode = C.CRYPT_E_NOT_FOUND & (1<<32 - 1)
	ErrMoreData       ErrorCode = C.ERROR_MORE_DATA & (1<<32 - 1)
)

Some C error codes translated to Go constants

func (ErrorCode) String

func (ec ErrorCode) String() string

type GOST2001KeyTransport

type GOST2001KeyTransport [172]byte

func (GOST2001KeyTransport) ToBlockEncryptedData

func (s GOST2001KeyTransport) ToBlockEncryptedData(dataStream []byte) BlockEncryptedData

type Gost2001KeyTransportASN1

type Gost2001KeyTransportASN1 struct {
	SessionKey          Gost28147_89EncryptedKey
	TransportParameters GostR3410TransportParameters `asn1:"tag:0,optional"`
}
GostR3410-KeyTransport ::= SEQUENCE {
  sessionEncryptedKey   Gost28147-89-EncryptedKey,
  transportParameters
    [0] IMPLICIT GostR3410-TransportParameters OPTIONAL
}

func (Gost2001KeyTransportASN1) ToBlockEncryptedData

func (k Gost2001KeyTransportASN1) ToBlockEncryptedData(dataStream []byte) (BlockEncryptedData, error)

type Gost28147_89EncryptedKey

type Gost28147_89EncryptedKey struct {
	EncryptedKey []byte
	MaskKey      []byte `asn1:"tag:0,optional"`
	MacKey       []byte
}
Gost28147-89-EncryptedKey ::=   SEQUENCE {
  encryptedKey         Gost28147-89-Key,
  maskKey              [0] IMPLICIT Gost28147-89-Key
                           OPTIONAL,
  macKey               Gost28147-89-MAC
}

type GostR3410TransportParameters

type GostR3410TransportParameters struct {
	EncryptionParamSet asn1.ObjectIdentifier
	EphemeralPublicKey SubjectPublicKeyInfo `asn1:"tag:0,optional"`
	SeanceVector       []byte
}
GostR3410-TransportParameters ::= SEQUENCE {
  encryptionParamSet   OBJECT IDENTIFIER,
  ephemeralPublicKey   [0] IMPLICIT SubjectPublicKeyInfo OPTIONAL,
  ukm                  OCTET STRING
}

type Hash

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

Hash encapsulates GOST hash

func NewHMAC

func NewHMAC(hashAlg asn1.ObjectIdentifier, key []byte) (_ *Hash, rErr error)

NewHMAC creates HMAC object initialized with given byte key

func NewHash

func NewHash(options HashOptions) (*Hash, error)

func (*Hash) BlockSize

func (h *Hash) BlockSize() int

BlockSize returns the hash's underlying block size. The Write method must be able to accept any amount of data, but it may operate more efficiently if all writes are a multiple of the block size.

func (*Hash) Close

func (h *Hash) Close() error

func (*Hash) Reset

func (h *Hash) Reset()

Reset resets the Hash to its initial state.

func (*Hash) Sign

func (h *Hash) Sign() ([]byte, error)

func (*Hash) Size

func (h *Hash) Size() int

Size returns the number of bytes Sum will return.

func (*Hash) Sum

func (h *Hash) Sum(b []byte) []byte

Sum appends the current hash to b and returns the resulting slice. It does not change the underlying hash state.

func (*Hash) Verify

func (h *Hash) Verify(signer Cert, sig []byte) error

func (*Hash) Write

func (h *Hash) Write(buf []byte) (n int, err error)

type HashOptions

type HashOptions struct {
	HashAlg  asn1.ObjectIdentifier // Hash algorithm ID
	SignCert Cert                  // Certificate with a reference to private key container used to sign the hash
	HMACKey  Key                   // HMAC key for creating hash in HMAC mode
}

HashOptions describe hash creation parameters

type Key

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

Key incapsulates key pair functions

func (Key) Close

func (key Key) Close() error

Close releases key handle.

func (Key) Decrypt

func (key Key) Decrypt(buf []byte, hash *Hash) ([]byte, error)

Decrypt byte data on given key

func (Key) Encode

func (key Key) Encode(cryptKey *Key) (SimpleBlob, error)

Encode exports a cryptographic key or a key pair in a secure manner. If cryptKey is nil, exports public key in unencrypted for, else -- session key.

func (Key) Encrypt

func (key Key) Encrypt(buf []byte, hash *Hash) ([]byte, error)

Encrypt byte data on given key

func (Key) GetAlgID

func (key Key) GetAlgID() (res C.ALG_ID, err error)

GetAlgID retrieves key's KP_ALGID parameter

func (Key) GetCipherOID

func (key Key) GetCipherOID() ([]byte, error)

GetCipherOID retrieves key's cipher OID

func (Key) GetDHOID

func (key Key) GetDHOID() (string, error)

GetDHOID retrieves key's DH OID

func (Key) GetHashOID

func (key Key) GetHashOID() (string, error)

GetHashOID retrieves key's HASH OID

func (Key) GetOID

func (key Key) GetOID() (string, error)

GetOID retrieves key's algorithm OID

func (Key) GetParam

func (key Key) GetParam(param KeyParamID) (res []byte, err error)

GetParam retrieves data that governs the operations of a key.

func (Key) IsZero

func (key Key) IsZero() bool

func (Key) SetAlgID

func (key Key) SetAlgID(algID C.ALG_ID) error

SetAlgID sets KP_ALGID parameter on the key

func (Key) SetCipherOID

func (key Key) SetCipherOID(oid []byte) error

SetCipherOID sets key's cipher OID

func (Key) SetIV

func (key Key) SetIV(iv []byte) error

SetIV sets key initialization vector

func (Key) SetMode

func (key Key) SetMode(mode C.DWORD) error

SetMode sets KP_MODE parameter on the key

func (Key) SetPadding

func (key Key) SetPadding(padding C.DWORD) error

SetPadding sets KP_PADDING parameter on the key

type KeyFlag

type KeyFlag C.DWORD

KeyFlag sets options on created key pair

const (
	KeyArchivable KeyFlag = C.CRYPT_ARCHIVABLE
	KeyExportable KeyFlag = C.CRYPT_EXPORTABLE
)

Key flags

type KeyPairID

type KeyPairID C.DWORD

KeyPairID selects public/private key pair from CSP container

const (
	AtKeyExchange KeyPairID = C.AT_KEYEXCHANGE
	AtSignature   KeyPairID = C.AT_SIGNATURE
)

Key specification

type KeyParamID

type KeyParamID C.DWORD

KeyParamID represents key parameters that can be retrieved for key.

const (
	KeyCertificateParam KeyParamID = C.KP_CERTIFICATE // X.509 certificate that has been encoded by using DER
)

Certificate parameter IDs

type Msg

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

Msg encapsulates stream decoder of PKCS7 message

func OpenToDecode

func OpenToDecode(dest io.Writer) (msg *Msg, rErr error)

OpenToDecode creates new Msg in decode mode. If detachedSig parameter is specified, it must contain detached P7S signature

func OpenToEncode

func OpenToEncode(dest io.Writer, options EncodeOptions) (msg *Msg, rErr error)

OpenToEncode creates new Msg in encode mode.

func OpenToEncrypt

func OpenToEncrypt(dest io.Writer, options EncryptOptions) (*Msg, error)

OpenToEncrypt creates new Msg in encrypt mode.

func OpenToVerify

func OpenToVerify(detachedSig ...[]byte) (msg *Msg, rErr error)

OpenToVerify creates new Msg in decode mode. If detachedSig parameter is specified, it must contain detached P7S signature

func (*Msg) CertStore

func (msg *Msg) CertStore() (res CertStore, err error)

CertStore returns message certificate store. As a side-effect, source stream is fully read and parsed.

func (*Msg) Close

func (msg *Msg) Close() error

Close needs to be called to release internal message handle and flush underlying encoded message.

func (*Msg) GetSignerCert

func (msg *Msg) GetSignerCert(i int, store CertStore) (Cert, error)

GetSignerCert returns i-th message signer certificate from provided certificate store (usually acquired by msg.CertStore() method).

func (*Msg) GetSignerCount

func (msg *Msg) GetSignerCount() (int, error)

GetSignerCount returns number of signer infos in message

func (*Msg) Verify

func (msg *Msg) Verify(c Cert) error

Verify verifies message signature against signer certificate

func (*Msg) Write

func (msg *Msg) Write(buf []byte) (int, error)

Write encodes provided bytes into message output data stream

type ProvType

type ProvType C.DWORD

ProvType is CryptoAPI provider type

const (
	ProvRsa          ProvType = C.PROV_RSA_FULL
	ProvGost94       ProvType = 71
	ProvGost2001     ProvType = 75
	ProvGost2012     ProvType = 80
	ProvGost2012_512 ProvType = 81
)

Provider types

type SessionKey

type SessionKey struct {
	SeanceVector       []byte
	EncryptedKey       []byte
	MACKey             []byte
	EncryptionParamSet []byte
}

func (SessionKey) ToSimpleBlob

func (s SessionKey) ToSimpleBlob() SimpleBlob

type SignParams

type SignParams struct {
	DHParamsOID asn1.ObjectIdentifier
	DigestOID   asn1.ObjectIdentifier
}

type SignerVerification

type SignerVerification struct {
	// Index is the position of this SignerInfo in the message.
	Index int
	// Subject and Issuer are populated only when WithSignerNames is used.
	Subject string
	Issuer  string
	// NotBefore and NotAfter are the signer certificate's validity bounds.
	NotBefore time.Time
	NotAfter  time.Time
	// SignatureErr is non-nil when the signature itself does not match the
	// data, or when the signer certificate could not be located.
	SignatureErr error
	// ChainStatus describes the outcome of chain evaluation. It is only
	// meaningful when SignatureErr is nil.
	ChainStatus ChainStatus
	// ChainErr is non-nil when chain evaluation could not be performed.
	ChainErr error
}

SignerVerification is the outcome for a single SignerInfo in a CMS message.

func (SignerVerification) OK

func (s SignerVerification) OK() bool

OK reports whether this signer passed every check.

func (SignerVerification) Reason

func (s SignerVerification) Reason() string

Reason returns a short human-readable explanation of why this signer failed, or an empty string when it passed.

type SimpleBlob

type SimpleBlob []byte

func (SimpleBlob) ToSessionKey

func (s SimpleBlob) ToSessionKey() (SessionKey, error)

type SubjectPublicKeyInfo

type SubjectPublicKeyInfo struct {
	Algorithm             AlgorithmIdentifier
	EncapsulatedPublicKey asn1.BitString
}

Jump to

Keyboard shortcuts

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