Documentation
¶
Overview ¶
Package cryptoprov provides a unified interface for cryptographic operations across different providers and hardware security modules (HSMs).
This package abstracts cryptographic operations to support:
- PKCS#11 compatible HSMs via the sibling crypto11 package
- AWS KMS for cloud-based key management
- Google Cloud KMS for cloud-based key management
- In-memory providers for testing and development
- Custom providers through the Provider interface
The package handles key generation, signing, encryption, and key management operations in a provider-agnostic way, allowing applications to switch between different cryptographic backends without code changes. Keys are RSA, ECDSA or ML-DSA (FIPS 204, post-quantum); an ML-DSA signer signs messages rather than digests, see MLDSASignerOptions.
Configuration is a small JSON or YAML token config whose Manufacturer field selects a loader registered with Register; provider packages register themselves in init(), so import them for side effects before calling Load.
A Provider creates and loads keys (KeyGenerator). A provider that is also a KeyManager lists its keys by page and filter, describes one with the fields a mask selects and destroys it; every provider of this module is one. A listing never returns a public key: KeyInfo does, on request.
A key of these providers is also a ContextSigner, whose SignContext a KMS request or a PKCS#11 session wait honours. SignContext signs with any crypto.Signer under a context, and BindContext hands one to an API that only calls Sign:
der, err := x509.CreateCertificate(rand.Reader, template, parent, pub, cryptoprov.BindContext(ctx, signer))
key, err := provider.GenerateKey(ctx, &cryptoprov.GenerateKeyRequest{
Label: "issuer-2026",
Type: certutil.KeyTypeECDSA,
Size: 384,
})
if err != nil {
return err
}
keyID, _, err := provider.IdentifyKey(ctx, key)
if err != nil {
return err
}
if km, ok := provider.(cryptoprov.KeyManager); ok {
info, err := km.KeyInfo(ctx, keyID, cryptoprov.KeyFieldMetadata|cryptoprov.KeyFieldPublicKey)
if err != nil {
return err
}
fmt.Println(info.Label, info.Type, info.Size, info.PublicKey)
}
Index ¶
- Constants
- Variables
- func AllKeys(ctx context.Context, km KeyManager, req *ListKeysRequest) iter.Seq2[*KeyInfo, error]
- func BindContext(ctx context.Context, signer crypto.Signer) crypto.Signer
- func DecryptContext(ctx context.Context, decrypter crypto.Decrypter, rand io.Reader, ...) ([]byte, error)
- func ECDSACurve(size int) (elliptic.Curve, error)
- func GcmDecrypt(ciphertext []byte, key []byte) ([]byte, error)
- func GcmEncrypt(plaintext []byte, key []byte) ([]byte, error)
- func GetPrivateKeyDERFromPEM(in []byte, password []byte) ([]byte, error)
- func MLDSAMu(pub *mldsa.PublicKey, context string, message []byte) ([]byte, error)
- func MLDSAParameters(size int) (mldsa.Parameters, error)
- func MLDSASignerOptions(opts crypto.SignerOpts) (mu bool, context string, err error)
- func MLDSASize(params mldsa.Parameters) int
- func MarkError(err, sentinel error) error
- func NewPageToken(req *ListKeysRequest, cursor PageCursor) (string, error)
- func ParsePrivateKeyDER(keyDER []byte) (crypto.PrivateKey, error)
- func ParsePrivateKeyPEM(keyPEM []byte) (key crypto.PrivateKey, err error)
- func ParsePrivateKeyPEMWithPassword(keyPEM []byte, password []byte) (key crypto.PrivateKey, err error)
- func Register(manufacturer string, loader ProviderLoader) error
- func Registered() []string
- func SignContext(ctx context.Context, signer crypto.Signer, rand io.Reader, digest []byte, ...) ([]byte, error)
- type ContextDecrypter
- type ContextSigner
- type Crypto
- func (c *Crypto) Add(p Provider) error
- func (c *Crypto) ByManufacturer(manufacturer, model string) (Provider, error)
- func (c *Crypto) Default() Provider
- func (c *Crypto) LoadPrivateKey(ctx context.Context, key []byte) (Provider, crypto.PrivateKey, error)
- func (c *Crypto) LoadTLSKeyPair(ctx context.Context, certFile, keyFile string) (*tls.Certificate, error)
- func (c *Crypto) NewSignerFromFromFile(ctx context.Context, caKeyFile string) (crypto.Signer, error)
- func (c *Crypto) NewSignerFromPEM(ctx context.Context, caKey []byte) (crypto.Signer, error)
- func (c *Crypto) TLSKeyPair(ctx context.Context, certPEMBlock, keyPEMBlock []byte) (*tls.Certificate, error)
- type GenerateKeyRequest
- type KeyFields
- type KeyFilter
- type KeyGenerator
- type KeyInfo
- type KeyManager
- type KeyState
- type KeyUsage
- type ListKeysRequest
- type ListKeysResponse
- type PageCursor
- type PrivateKeyURI
- type Provider
- type ProviderLoader
- type TokenConfig
- type TokenInfo
- type TokenManager
Constants ¶
const ( // DefaultPageSize is the page size of a provider without a backend page // of its own (PKCS#11, the in-memory providers) when // ListKeysRequest.PageSize is zero. DefaultPageSize = 100 // MaxPageSize is the largest page a provider returns; a larger // ListKeysRequest.PageSize is cut to it. MaxPageSize = 1000 )
const ( // MLDSA44, MLDSA65 and MLDSA87 are the FIPS 204 parameter set numbers as // csr.KeyRequest.Size and certutil.KeyInfo.KeySize carry them. MLDSA44 = 44 MLDSA65 = 65 MLDSA87 = 87 // MetaParameterSet is the KeyInfo.Meta key under which a provider // reports the parameter set of an ML-DSA key, for example "ML-DSA-65". MetaParameterSet = "parameter_set" // MLDSAMuSize is the length in bytes of the ML-DSA message // representative μ (FIPS 204, Algorithm 7) that a signer accepts with // crypto.MLDSAMu. MLDSAMuSize = 64 )
Variables ¶
var ErrDuplicateProvider = errors.New("duplicate provider")
ErrDuplicateProvider is returned by Crypto.Add, New and Load when a different provider is already registered for the same manufacturer and model.
var ErrInvalidPageToken = errors.New("invalid page token")
ErrInvalidPageToken is the cause of the error ListKeys returns for a ListKeysRequest.PageToken that is malformed or was issued for another Filter or Fields.
var ErrInvalidPrivateKeyURI = errors.New("invalid URI for private key object")
ErrInvalidPrivateKeyURI is returned if the PKCS #11 URI is invalid for the private key object
var ErrInvalidURI = errors.New("invalid URI")
ErrInvalidURI is returned if the PKCS #11 URI is invalid.
var ErrKeyNotFound = errors.New("key not found")
ErrKeyNotFound is the cause of the error GetKey, KeyInfo, ExportKey and DestroyKey return for a key the provider does not have.
var ErrNilProvider = errors.New("nil provider")
ErrNilProvider is returned by New and Crypto.Add for a nil provider, including a typed nil such as a nil *crypto11.PKCS11Lib.
var ErrNotSupported = errors.New("not supported by the provider")
ErrNotSupported is the cause of the error a provider returns for a request it understands and its backend cannot serve: a filter on tags on a PKCS#11 token, an encryption key on a KMS provider, a key size the backend does not offer. It is never reported as an empty result.
Functions ¶
func AllKeys ¶
func AllKeys(ctx context.Context, km KeyManager, req *ListKeysRequest) iter.Seq2[*KeyInfo, error]
AllKeys iterates over the keys of every page of the listing req describes, starting at req.PageToken; req is not modified. An error ends the iteration: it is yielded once, with a nil key. A page without keys is not the end, only an empty NextPageToken is.
for key, err := range cryptoprov.AllKeys(ctx, km, req) {
if err != nil {
return err
}
fmt.Println(key.ID, key.Label)
}
func BindContext ¶ added in v2.0.328
BindContext returns a crypto.Signer whose Sign is signer's SignContext with ctx, for an API that only calls Sign, such as x509.CreateCertificate, x509.CreateCertificateRequest or ocsp.CreateResponse:
der, err := x509.CreateCertificate(rand.Reader, template, parent, pub, cryptoprov.BindContext(ctx, signer))
The bound Sign is SignContext(ctx, signer, ...): a ContextSigner signs with ctx, any other signer once ctx is checked. The bound signer has Public and Sign, and SignMessage when signer is a crypto.MessageSigner but not a ContextSigner (SignMessage takes no context, so a ContextSigner signs through the bound Sign); it hides every other method and the concrete type of signer, so bind at the call and keep signer for type checks such as csr.SignatureAlgorithmer. It must not be used after ctx ends.
func DecryptContext ¶ added in v2.0.328
func DecryptContext(ctx context.Context, decrypter crypto.Decrypter, rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) ([]byte, error)
DecryptContext decrypts ciphertext with decrypter under ctx. A ContextDecrypter gets ctx through DecryptContext; any other decrypter is called through Decrypt after ctx is checked.
func ECDSACurve ¶
ECDSACurve returns the curve of an ECDSA key size as GenerateKeyRequest.Size carries it: 256, 384 or 521. Any other size is an error.
func GcmDecrypt ¶
GcmDecrypt returns decrypted blob with GCM cipher
func GcmEncrypt ¶
GcmEncrypt returns encrypted blob with GCM cipher
func GetPrivateKeyDERFromPEM ¶
GetPrivateKeyDERFromPEM parses a PEM-encoded private key and returns DER-format key bytes.
func MLDSAMu ¶
MLDSAMu returns μ, the message representative an ML-DSA signature is computed over (FIPS 204, Algorithm 7): SHAKE256(tr ‖ 0x00 ‖ len(context) ‖ context ‖ message, 64) with tr = SHAKE256(pk, 64). A KMS or HSM external-μ operation over it produces the same signature as signing message with context locally, which mldsa.Verify checks with the same message and context. The context is at most 255 bytes.
func MLDSAParameters ¶
func MLDSAParameters(size int) (mldsa.Parameters, error)
MLDSAParameters returns the ML-DSA parameter set for its FIPS 204 number: MLDSA44, MLDSA65 or MLDSA87. Any other number is an error.
func MLDSASignerOptions ¶
func MLDSASignerOptions(opts crypto.SignerOpts) (mu bool, context string, err error)
MLDSASignerOptions validates opts against the contract every ML-DSA signer of this module follows: ML-DSA signs a message, not a digest. The signer accepts the message with nil options, options whose HashFunc is zero (x509.CreateCertificate passes crypto.Hash(0)) or *mldsa.Options carrying an optional context string (a nil *mldsa.Options counts as nil), and a 64-byte message representative μ with crypto.MLDSAMu. Any other hash, and a nil pointer of any other options type, is an error, so a hash-then-sign caller fails instead of signing a digest as if it were the message. It returns whether the message is a μ and the context.
func MLDSASize ¶
func MLDSASize(params mldsa.Parameters) int
MLDSASize returns the FIPS 204 number of an ML-DSA parameter set, MLDSA44, MLDSA65 or MLDSA87, as GenerateKeyRequest.Size and KeyInfo.Size carry it, and 0 for any other value. It is the inverse of MLDSAParameters.
func MarkError ¶
MarkError returns err with sentinel as an additional identity: errors.Is(result, sentinel) is true, with the standard library as with cockroachdb/errors, the message is that of err, and errors.As still finds the causes of err. A provider uses it to report a backend error, such as the "not found" of a KMS, as ErrKeyNotFound without losing the service error. A nil err stays nil.
func NewPageToken ¶
func NewPageToken(req *ListKeysRequest, cursor PageCursor) (string, error)
NewPageToken returns the page token that resumes the listing of req at cursor. It is for provider implementations.
func ParsePrivateKeyDER ¶
func ParsePrivateKeyDER(keyDER []byte) (crypto.PrivateKey, error)
ParsePrivateKeyDER parses a PKCS #1, PKCS #8, ECDSA DER-encoded private key. The key must not be in PEM format. PKCS #8 keys may be RSA, ECDSA, Ed25519 or ML-DSA; an ML-DSA key must be in the seed form (RFC 9881), the form x509.MarshalPKCS8PrivateKey and "openssl genpkey -provparam ml-dsa.output_formats=seed-only" write.
func ParsePrivateKeyPEM ¶
func ParsePrivateKeyPEM(keyPEM []byte) (key crypto.PrivateKey, err error)
ParsePrivateKeyPEM parses and returns a PEM-encoded private key. The private key may be either an unencrypted PKCS#8, PKCS#1, or elliptic private key; see ParsePrivateKeyDER for the key types.
func ParsePrivateKeyPEMWithPassword ¶
func ParsePrivateKeyPEMWithPassword(keyPEM []byte, password []byte) (key crypto.PrivateKey, err error)
ParsePrivateKeyPEMWithPassword parses and returns a PEM-encoded private key. The private key may be an unencrypted PKCS#8, PKCS#1, or SEC1 key, or a legacy PEM block encrypted per RFC 1423 (Proc-Type: 4,ENCRYPTED); encrypted PKCS#8 (ENCRYPTED PRIVATE KEY) is not supported. The key may be RSA, ECDSA, Ed25519 or ML-DSA (the last two PKCS#8 only).
func Register ¶
func Register(manufacturer string, loader ProviderLoader) error
Register provider loader by manufacturer
func SignContext ¶ added in v2.0.328
func SignContext(ctx context.Context, signer crypto.Signer, rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
SignContext signs digest with signer under ctx. A ContextSigner gets ctx through SignContext; any other signer is called through Sign after ctx is checked, since it cannot be interrupted.
Types ¶
type ContextDecrypter ¶ added in v2.0.328
type ContextDecrypter interface {
crypto.Decrypter
// DecryptContext is Decrypt under ctx: it returns an error that wraps
// ctx.Err() when ctx ends before the plaintext is produced.
DecryptContext(ctx context.Context, rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) ([]byte, error)
}
ContextDecrypter is a crypto.Decrypter whose decryption can be bounded or cancelled by a context, as ContextSigner is for signing. The RSA keys of crypto11 and of the in-memory providers are ContextDecrypters.
type ContextSigner ¶ added in v2.0.328
type ContextSigner interface {
crypto.Signer
// SignContext is Sign under ctx: it returns an error that wraps
// ctx.Err() when ctx ends before the signature is produced.
SignContext(ctx context.Context, rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
}
ContextSigner is a crypto.Signer whose signature can be bounded or cancelled by a context: a KMS signer passes ctx to its SDK call, and a PKCS#11 signer waits for a pooled session no longer than ctx allows. Sign of such a signer is SignContext with context.Background(). Every signer of the providers of this module is one; use SignContext to sign with any crypto.Signer, and BindContext to hand ctx to an API that calls Sign.
type Crypto ¶
type Crypto struct {
// contains filtered or unexported fields
}
Crypto exposes instances of Provider, found by manufacturer and model. It is safe for concurrent use: Add may run while other goroutines call ByManufacturer or LoadPrivateKey.
func Load ¶
Load returns Crypto with loaded providers from the given config locations. Each config must name a different manufacturer and model than the others (ErrDuplicateProvider). On error, Load closes the providers it already loaded that implement Close() error.
func New ¶
New creates an instance of Crypto providers. defaultProvider is required; providers are added with Add, so a nil entry or a conflicting duplicate fails New.
func (*Crypto) Add ¶
Add registers p for lookup by its manufacturer and model. Adding the same provider again, including the default one, is a no-op when its dynamic value is comparable, such as a pointer; the provider types in this module are. A provider value that is not comparable (a struct holding a map, slice or func) can not be matched, so adding it again returns ErrDuplicateProvider. A different provider with the manufacturer and model of a registered or the default provider returns ErrDuplicateProvider (XPKI-016), and a nil provider, including a typed nil, returns ErrNilProvider.
func (*Crypto) ByManufacturer ¶
ByManufacturer returns the default provider or the registered provider for manufacturer and model. It does not lock and may run concurrently with Add.
func (*Crypto) LoadPrivateKey ¶
func (c *Crypto) LoadPrivateKey(ctx context.Context, key []byte) (Provider, crypto.PrivateKey, error)
LoadPrivateKey returns crypto.PrivateKey. The input key can be in PEM encoded format, or PKCS11 URI. A URI is resolved by the provider it names with ctx, which bounds the KMS requests or the wait for a PKCS#11 session; the returned Provider is nil for a PEM key.
func (*Crypto) LoadTLSKeyPair ¶
func (c *Crypto) LoadTLSKeyPair(ctx context.Context, certFile, keyFile string) (*tls.Certificate, error)
LoadTLSKeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf holds the parsed leaf certificate. ctx is for a key file that holds a pkcs11: URI, see LoadPrivateKey.
func (*Crypto) NewSignerFromFromFile ¶
func (c *Crypto) NewSignerFromFromFile(ctx context.Context, caKeyFile string) (crypto.Signer, error)
NewSignerFromFromFile returns the signer of the key in caKeyFile, which holds a PEM encoded key or a PKCS#11 URI; ctx is for the URI, see LoadPrivateKey.
func (*Crypto) NewSignerFromPEM ¶
NewSignerFromPEM returns the signer of caKey, a PEM encoded key or a PKCS#11 URI; ctx is for the URI, see LoadPrivateKey.
func (*Crypto) TLSKeyPair ¶
func (c *Crypto) TLSKeyPair(ctx context.Context, certPEMBlock, keyPEMBlock []byte) (*tls.Certificate, error)
TLSKeyPair parses a public/private key pair from PEM encoded data. The key may be a PEM private key or a pkcs11: URI resolved through the registered providers with ctx. On successful return, Certificate.Leaf holds the parsed leaf certificate. An error is returned when the private key does not match the leaf certificate's public key.
type GenerateKeyRequest ¶
type GenerateKeyRequest struct {
// Label names the key: CKA_LABEL, the AWS description and alias, the
// GCP "label" label and key id prefix. It may be empty: the PKCS#11 and
// in-memory providers then generate one, and the KMS providers create
// the key without a label.
Label string
// Type is the key algorithm: certutil.KeyTypeRSA, KeyTypeECDSA or
// KeyTypeMLDSA.
Type string
// Size is the RSA modulus size in bits, the ECDSA curve size (256, 384
// or 521) or the ML-DSA parameter set (MLDSA44, MLDSA65 or MLDSA87).
Size int
// Usage is what the key is for; zero means KeyUsageSign.
Usage KeyUsage
// Tags are attached to the key as AWS tags or GCP labels. A provider
// without tags returns ErrNotSupported when they are set.
Tags map[string]string
}
GenerateKeyRequest asks KeyGenerator.GenerateKey for a new key.
func (*GenerateKeyRequest) KeyUsage ¶
func (r *GenerateKeyRequest) KeyUsage() KeyUsage
KeyUsage returns the usage of the key to create: Usage, or KeyUsageSign when it is zero.
func (*GenerateKeyRequest) Validate ¶
func (r *GenerateKeyRequest) Validate() error
Validate reports a request no provider can serve: an unknown type, a size the type does not have, or a usage the type cannot have (only an RSA key encrypts). It does not know what a backend offers: a provider answers a valid request it cannot serve with ErrNotSupported. Providers call it before any request to their backend.
type KeyFields ¶
type KeyFields uint
KeyFields selects the groups of KeyInfo fields a call fills. ID and Name are always filled.
const ( // KeyFieldMetadata selects Label, Type, Size, Usage, Class and // CreationTime. KeyFieldMetadata KeyFields = 1 << iota // KeyFieldState selects State and CurrentVersionID. KeyFieldState // KeyFieldTags selects Tags. KeyFieldTags // KeyFieldPublicKey selects PublicKey. It is valid for // KeyManager.KeyInfo only: no listing fetches a public key. KeyFieldPublicKey // KeyFieldsAll selects every group a listing can fill. KeyFieldsAll = KeyFieldMetadata | KeyFieldState | KeyFieldTags )
type KeyFilter ¶
type KeyFilter struct {
// Usage keeps a key with at least one of these usages.
Usage KeyUsage
// Types keeps a key whose KeyInfo.Type is one of these.
Types []string
// Label keeps a key with exactly this label.
Label string
// LabelPrefix keeps a key whose label starts with this.
LabelPrefix string
// Tags keeps a key that has every one of these tags with this value.
Tags map[string]string
// States keeps a key in one of these states. Empty keeps every state,
// including a key that is pending deletion.
States []KeyState
}
KeyFilter keeps the keys that pass every condition that is set; the zero filter keeps every key the backend lists.
func (*KeyFilter) Fields ¶
Fields returns the KeyInfo groups Match reads for the conditions that are set, which a provider has to fill before it can evaluate the filter itself.
type KeyGenerator ¶
type KeyGenerator interface {
// GenerateKey creates the key req describes and returns its handle. It
// calls req.Validate first; a valid request the backend cannot serve
// (an encryption key on a KMS provider, tags on a PKCS#11 token, a size
// the backend does not offer) is a wrapped ErrNotSupported.
GenerateKey(ctx context.Context, req *GenerateKeyRequest) (crypto.PrivateKey, error)
// GetKey returns the handle of the key keyID, the KeyInfo.ID of a
// listing or the id attribute of a key URI. A key the provider does not
// have is a wrapped ErrKeyNotFound.
GetKey(ctx context.Context, keyID string) (crypto.PrivateKey, error)
// IdentifyKey returns the ID and the label of a handle this provider
// returned.
IdentifyKey(ctx context.Context, key crypto.PrivateKey) (keyID, label string, err error)
// ExportKey returns what a configuration stores to load the key again:
// the PEM encoded key from a provider with exportable keys (uri is then
// empty), otherwise the pkcs11: URI of the key, which
// Crypto.LoadPrivateKey resolves.
ExportKey(ctx context.Context, keyID string) (uri string, key []byte, err error)
}
KeyGenerator creates keys and returns handles to them. A handle is a crypto.Signer for a signing key and a crypto.Decrypter for an encryption key; an ML-DSA signer follows the contract MLDSASignerOptions describes. Every method takes the caller's context: a KMS provider passes it to its requests, and crypto11, whose PKCS#11 calls cannot be cancelled, checks it before the call and while it waits for a session.
type KeyInfo ¶
type KeyInfo struct {
// ID identifies the key to GetKey, KeyInfo, ExportKey and DestroyKey:
// CKA_ID on a PKCS#11 token, the key id (UUID) on AWS KMS, the CryptoKey
// id on Google Cloud KMS ("K", or "K/cryptoKeyVersions/N" when the call
// named a version).
ID string
// Name is the full resource name of a cloud key: the AWS key ARN, the
// GCP resource name. Empty on PKCS#11 and in-memory providers.
Name string
// Label is the name the key was created with (KeyFieldMetadata):
// CKA_LABEL, the AWS key description, the GCP "label" label.
Label string
// Type is the key algorithm (KeyFieldMetadata): certutil.KeyTypeRSA,
// KeyTypeECDSA or KeyTypeMLDSA, and empty for a key of another family,
// whose native spec is in Meta.
Type string
// Size is the RSA modulus size in bits, the ECDSA curve size or the
// ML-DSA parameter set number (KeyFieldMetadata), as
// csr.KeyRequest.Size and certutil.KeyInfo.KeySize carry it; zero when
// Type is empty or the backend does not tell.
Size int
// Usage is what the key is for (KeyFieldMetadata); zero for a usage
// other than signing and encryption, whose native name is in Meta.
Usage KeyUsage
// Class is the PKCS#11 object class name (KeyFieldMetadata); empty on
// the other providers.
Class string
// CreationTime is when the key was created (KeyFieldMetadata); nil when
// the backend does not tell, as on PKCS#11.
CreationTime *time.Time
// State is the state of the key, or on Google Cloud KMS of the version
// CurrentVersionID names (KeyFieldState). A PKCS#11 key is always
// enabled.
State KeyState
// CurrentVersionID is the key version the call described
// (KeyFieldState); empty on a provider without key versions.
CurrentVersionID string
// Tags are the AWS resource tags or GCP labels of the key
// (KeyFieldTags).
Tags map[string]string
// PublicKey is the PEM encoded public key (KeyFieldPublicKey, from
// KeyManager.KeyInfo only).
PublicKey string
// Meta carries provider-specific details for display, such as the
// native usage, origin and algorithm names. For an ML-DSA key it has
// MetaParameterSet, for example "ML-DSA-65". Do not parse it: the typed
// fields above carry what callers decide on.
Meta map[string]string
}
KeyInfo describes a key. A call fills ID and Name, the groups its KeyFields select and whatever else the provider has without another request; a field that was neither selected nor free is zero. The design document Documentation/design/keymanager.md has the source of each field per provider.
type KeyManager ¶
type KeyManager interface {
// ListKeys returns one page of the keys that pass req.Filter, with the
// fields req.Fields selects, and never a public key. A page can hold
// fewer keys than req.PageSize, or none, and still have a
// NextPageToken: the listing ends when that is empty (AllKeys hides the
// loop). A condition the provider cannot evaluate is a wrapped
// ErrNotSupported and a token of another request a wrapped
// ErrInvalidPageToken. A failure returns no partial page.
ListKeys(ctx context.Context, req *ListKeysRequest) (*ListKeysResponse, error)
// KeyInfo describes the key keyID with the fields the mask selects;
// KeyFieldPublicKey adds the PEM public key, which no other call
// returns. A key the provider does not have is a wrapped
// ErrKeyNotFound.
KeyInfo(ctx context.Context, keyID string, fields KeyFields) (*KeyInfo, error)
// DestroyKey destroys the key keyID, or schedules its destruction on a
// backend that defers it (AWS KMS, Google Cloud KMS).
DestroyKey(ctx context.Context, keyID string) error
}
KeyManager lists, describes and destroys the keys of the provider's store: the token it is logged in to, the AWS account and Region, the Google Cloud key ring. It is optional: callers type-assert a Provider. The rules of a listing are in Documentation/design/keymanager.md.
type KeyState ¶
type KeyState string
KeyState is the state of a key, or of the key version a KeyInfo describes.
const ( // KeyStateEnabled is a key that can be used. KeyStateEnabled KeyState = "enabled" // KeyStateDisabled is a key that cannot be used until it is enabled // again. KeyStateDisabled KeyState = "disabled" // KeyStatePendingDeletion is a key scheduled for deletion, which the // backend may still cancel. KeyStatePendingDeletion KeyState = "pending_deletion" // KeyStateDestroyed is a key whose material is gone. KeyStateDestroyed KeyState = "destroyed" // used: being created, waiting for imported material, a failed // generation. The native state is in KeyInfo.Meta. KeyStateUnavailable KeyState = "unavailable" )
func ParseKeyState ¶
ParseKeyState parses a KeyState, case-insensitively.
type KeyUsage ¶
type KeyUsage uint
KeyUsage is a set of the operations a key is for. The values are those of csr.KeyPurpose, so KeyUsage(csr.SigningKey) is KeyUsageSign.
func ParseKeyUsage ¶
ParseKeyUsage parses the String form of a KeyUsage: "sign", "encrypt" or both separated by a comma, case-insensitively. An empty string is no usage.
type ListKeysRequest ¶
type ListKeysRequest struct {
// PageSize is the largest number of keys to return. Zero means the
// provider default, and a value above MaxPageSize is cut to it.
PageSize int
// PageToken is the NextPageToken of the previous page, with the same
// Filter and Fields; empty for the first page.
PageToken string
// Filter selects the keys.
Filter KeyFilter
// Fields selects what to fill besides ID and Name. KeyFieldPublicKey is
// an error.
Fields KeyFields
}
ListKeysRequest asks KeyManager.ListKeys for one page of keys.
func (*ListKeysRequest) Limit ¶
func (r *ListKeysRequest) Limit(defaultSize int) int
Limit returns the number of keys a page of the request holds at most: PageSize, defaultSize (or DefaultPageSize) when it is zero, and never more than MaxPageSize.
func (*ListKeysRequest) Validate ¶
func (r *ListKeysRequest) Validate() error
Validate reports a request no provider accepts: a negative page size, a field mask that asks a listing for the public key or has unknown groups, or an invalid filter. The page token is checked by the provider it is for.
type ListKeysResponse ¶
type ListKeysResponse struct {
// Keys are the keys of the page, at most the page size. A page can hold
// fewer keys than asked for, or none, while NextPageToken is set.
Keys []KeyInfo
// NextPageToken resumes the listing after this page; empty after the
// last page.
NextPageToken string
}
ListKeysResponse is one page of a listing.
func PageKeys ¶
func PageKeys(req *ListKeysRequest, keys []KeyInfo) (*ListKeysResponse, error)
PageKeys answers req from keys, the complete list of a provider that holds its keys in memory, in a stable order: it validates the request, skips the candidates the page token has passed, applies the filter and returns at most a page with the token of the next one. Every key must have the groups the filter reads; the keys are returned as they are, whatever req.Fields selects. The token is an offset in keys, so a key added or removed between two pages can be repeated or missed.
type PageCursor ¶
type PageCursor struct {
// Source names the candidate source the listing reads, for a provider
// with more than one.
Source string `json:"s,omitempty"`
// Marker is the backend's own marker or page token of the page the
// listing resumes in.
Marker string `json:"m,omitempty"`
// Offset is the number of candidates of that page, or of the whole
// search order, the listing has examined.
Offset int `json:"o,omitempty"`
}
PageCursor is where a listing resumes. A provider keeps it in ListKeysResponse.NextPageToken with NewPageToken and reads it back from the next request with ParsePageToken; callers treat the token as opaque.
func ParsePageToken ¶
func ParsePageToken(req *ListKeysRequest) (PageCursor, error)
ParsePageToken returns the cursor of req.PageToken, the zero cursor for an empty token, or a wrapped ErrInvalidPageToken for a token that is malformed, has a negative offset or was issued for another Filter or Fields. It is for provider implementations.
type PrivateKeyURI ¶
type PrivateKeyURI interface {
// Token manufacturer
Manufacturer() string
// Model manufacturer
Model() string
// Token serial number
TokenSerial() string
// Token label
TokenLabel() string
// Key ID
ID() string
}
PrivateKeyURI holds PKCS#11 private key information.
A token may be identified either by serial number or label. If both are specified then the first match wins.
func ParsePrivateKeyURI ¶
func ParsePrivateKeyURI(uri string) (PrivateKeyURI, error)
ParsePrivateKeyURI parses a PKCS #11 URI (RFC 7512) into a key configuration. The URI must have type=private, serial and id (the id is percent-decoded and may hold binary data). Query attributes are validated like ParseTokenURI does but not returned.
type Provider ¶
type Provider interface {
KeyGenerator
Manufacturer() string
Model() string
}
Provider is a key backend: a PKCS#11 token, a cloud KMS or an in-process store. Manufacturer and Model identify it in Crypto and in key URIs.
func LoadProvider ¶
LoadProvider load a single provider
type ProviderLoader ¶
type ProviderLoader func(cfg TokenConfig) (Provider, error)
ProviderLoader is interface for loading provider by manufacturer
func Unregister ¶
func Unregister(manufacturer string) (ProviderLoader, error)
Unregister provider loader by manufacturer
type TokenConfig ¶
type TokenConfig interface {
// Manufacturer name of the manufacturer
Manufacturer() string
// Model name of the device
Model() string
// Full path to PKCS#11 library
Path() string
// Token serial number
TokenSerial() string
// Token label
TokenLabel() string
// Pin is a secret to access the token.
// If it's prefixed with `file:`, then it will be loaded from the file.
Pin() string
// Comma separated key=value pair of attributes(e.g. "ServiceName=x,UserName=y")
Attributes() string
}
TokenConfig holds PKCS#11 configuration information.
A token may be identified by serial number, label, or both; how they are used is provider specific. The PKCS#11 provider (crypto11) requires at least one of them and selects the first token matching every nonempty one.
Supply this to Configure(), or alternatively use ConfigureFromFile().
func LoadTokenConfig ¶
func LoadTokenConfig(filename string) (TokenConfig, error)
LoadTokenConfig loads PKCS#11 token configuration
func ParseTokenURI ¶
func ParseTokenURI(uri string) (TokenConfig, error)
ParseTokenURI parses a PKCS #11 URI (RFC 7512) into a token configuration. The path attributes manufacturer, model, token and serial select the token; the query attributes module-name, module-path, pin-value and pin-source (a file: URI whose content, trimmed, is the PIN) set the library and the PIN. module-path overrides module-name when both are present. The query attributes are also accepted in the path, as this package did before XPKI-027, but not in both places, and a URI with both pin-source and pin-value is refused (RFC 7512 §2.4). Manufacturer and model are trimmed. Errors never contain a pin-value.
type TokenInfo ¶
type TokenInfo struct {
// SlotID is the slot the token is in; TokenManager.Token takes it.
SlotID uint
// Description is the slot description.
Description string
// Label is the token label.
Label string
// Manufacturer is the token manufacturer.
Manufacturer string
// Model is the token model.
Model string
// Serial is the token serial number.
Serial string
// Current reports the token the provider is logged in to: the store its
// own KeyManager methods work on.
Current bool
}
TokenInfo describes a token of a provider with several stores, which is a PKCS#11 module with its slots.
type TokenManager ¶
type TokenManager interface {
// ListTokens returns the tokens of the provider; TokenInfo.Current
// marks the one it is logged in to.
ListTokens(ctx context.Context) ([]TokenInfo, error)
// Token returns the KeyManager of the token in slot slotID.
Token(slotID uint) (KeyManager, error)
}
TokenManager is implemented by a provider with several stores, which is crypto11 with the slots of its PKCS#11 module. The KeyManager methods of the provider itself work on the token it is logged in to.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package awskmscrypto implements cryptoprov.Provider and cryptoprov.KeyManager over AWS KMS asymmetric signing keys (RSA 2048/3072/4096, NIST P-256, P-384, P-521 and ML-DSA-44/65/87).
|
Package awskmscrypto implements cryptoprov.Provider and cryptoprov.KeyManager over AWS KMS asymmetric signing keys (RSA 2048/3072/4096, NIST P-256, P-384, P-521 and ML-DSA-44/65/87). |
|
Package gcpkmscrypto implements cryptoprov.Provider and cryptoprov.KeyManager over Google Cloud KMS (HSM protection level).
|
Package gcpkmscrypto implements cryptoprov.Provider and cryptoprov.KeyManager over Google Cloud KMS (HSM protection level). |
|
Package inmemcrypto is a software cryptoprov.Provider that keeps RSA, ECDSA and ML-DSA keys in memory and can export them as PEM (PKCS#1, SEC1 and PKCS#8 respectively).
|
Package inmemcrypto is a software cryptoprov.Provider that keeps RSA, ECDSA and ML-DSA keys in memory and can export them as PEM (PKCS#1, SEC1 and PKCS#8 respectively). |
|
Package testprov is a test-only in-memory cryptoprov.Provider (RSA, ECDSA and ML-DSA keys) whose keys are not exportable: ExportKey returns a pkcs11: URI like the HSM and KMS providers do, and the key wrapper implements crypto.Decrypter.
|
Package testprov is a test-only in-memory cryptoprov.Provider (RSA, ECDSA and ML-DSA keys) whose keys are not exportable: ExportKey returns a pkcs11: URI like the HSM and KMS providers do, and the key wrapper implements crypto.Decrypter. |