Documentation
¶
Overview ¶
Package crypto11 provides a Go interface to PKCS#11 cryptographic devices such as Hardware Security Modules (HSMs) and smart cards.
This package implements the standard Go crypto interfaces for:
- RSA private keys and signatures
- ECDSA private keys and signatures
- Random number generation
- Session management
The package supports common PKCS#11 operations including:
- Key generation on the device
- Signing operations using device-stored keys
- Object discovery and management
- Session pooling for performance
Keys generated or imported into the HSM cannot be exported, providing hardware-level protection for cryptographic operations.
Open a token with Init or ConfigureFromFile and release it with Close. Every PKCS11Lib on the same library path shares one loaded module: the first one initializes it and the last Close finalizes it. Each PKCS11Lib keeps at most WithMaxSessions pooled sessions per slot (default DefaultMaxSessions); an operation waits while all of them are in use.
lib, err := crypto11.ConfigureFromFile("/path/softhsm.json", crypto11.WithMaxSessions(64))
if err != nil {
return err
}
defer func() { _ = lib.Close() }()
key, err := lib.GenerateECDSAKeyPair(ctx, elliptic.P256())
if err != nil {
return err
}
sig, err := key.Sign(rand.Reader, digest, crypto.SHA256)
A PKCS11Lib is the cryptoprov.Provider and cryptoprov.KeyManager of the token it is logged in to, and a cryptoprov.TokenManager for the other tokens of the module. The methods that take a context wait for a session no longer than it allows; a PKCS#11 call that has started is not interrupted, and Sign and Decrypt, which have no context, wait without a deadline.
This package is based on github.com/ThalesIgnite/crypto11 with modifications for integration with the xpki ecosystem.
Index ¶
- Constants
- Variables
- func ConvertToPublic(priv crypto.PrivateKey) (crypto.PublicKey, error)
- func LoadProvider(cfg cryptoprov.TokenConfig) (cryptoprov.Provider, error)
- func UlongToBytes(n uint) []byte
- type KeyIdentifier
- type Option
- type PKCS11Lib
- func (lib *PKCS11Lib) Close() error
- func (lib *PKCS11Lib) CurrentSlotID() uint
- func (lib *PKCS11Lib) DestroyKey(ctx context.Context, keyID string) error
- func (lib *PKCS11Lib) ExportKey(ctx context.Context, keyID string) (string, []byte, error)
- func (lib *PKCS11Lib) FindKeyPair(ctx context.Context, keyID, label string) (crypto.PrivateKey, error)
- func (lib *PKCS11Lib) FindKeyPairOnSession(session pkcs11.SessionHandle, slot uint, keyID, label string) (crypto.PrivateKey, error)
- func (lib *PKCS11Lib) FindKeyPairOnSlot(ctx context.Context, slot uint, keyID, label string) (crypto.PrivateKey, error)
- func (lib *PKCS11Lib) GenRandom(data []byte) (n int, err error)
- func (lib *PKCS11Lib) GenerateECDSAKeyPair(ctx context.Context, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
- func (lib *PKCS11Lib) GenerateECDSAKeyPairOnSession(session pkcs11.SessionHandle, slot uint, id []byte, label []byte, ...) (*PKCS11PrivateKeyECDSA, error)
- func (lib *PKCS11Lib) GenerateECDSAKeyPairOnSlot(ctx context.Context, slot uint, id []byte, label []byte, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
- func (lib *PKCS11Lib) GenerateECDSAKeyPairWithLabel(ctx context.Context, label string, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
- func (lib *PKCS11Lib) GenerateKey(ctx context.Context, req *cryptoprov.GenerateKeyRequest) (crypto.PrivateKey, error)
- func (lib *PKCS11Lib) GenerateMLDSAKeyPairOnSlot(ctx context.Context, slot uint, id []byte, label []byte, ...) (*PKCS11PrivateKeyMLDSA, error)
- func (lib *PKCS11Lib) GenerateMLDSAKeyPairWithLabel(ctx context.Context, label string, params mldsa.Parameters) (*PKCS11PrivateKeyMLDSA, error)
- func (lib *PKCS11Lib) GenerateRSAKeyPair(ctx context.Context, bits int, usage cryptoprov.KeyUsage) (*PKCS11PrivateKeyRSA, error)
- func (lib *PKCS11Lib) GenerateRSAKeyPairOnSession(session pkcs11.SessionHandle, slot uint, id []byte, label []byte, bits int, ...) (*PKCS11PrivateKeyRSA, error)
- func (lib *PKCS11Lib) GenerateRSAKeyPairOnSlot(ctx context.Context, slot uint, id []byte, label []byte, bits int, ...) (*PKCS11PrivateKeyRSA, error)
- func (lib *PKCS11Lib) GenerateRSAKeyPairWithLabel(ctx context.Context, label string, bits int, usage cryptoprov.KeyUsage) (*PKCS11PrivateKeyRSA, error)
- func (lib *PKCS11Lib) GetKey(ctx context.Context, keyID string) (crypto.PrivateKey, error)
- func (lib *PKCS11Lib) Identify(ctx context.Context, object *PKCS11Object) (keyID, label string, err error)
- func (lib *PKCS11Lib) IdentifyKey(ctx context.Context, priv crypto.PrivateKey) (keyID, label string, err error)
- func (lib *PKCS11Lib) KeyInfo(ctx context.Context, keyID string, fields cryptoprov.KeyFields) (*cryptoprov.KeyInfo, error)
- func (lib *PKCS11Lib) ListKeys(ctx context.Context, req *cryptoprov.ListKeysRequest) (*cryptoprov.ListKeysResponse, error)
- func (lib *PKCS11Lib) ListTokens(ctx context.Context) ([]cryptoprov.TokenInfo, error)
- func (lib *PKCS11Lib) Manufacturer() string
- func (lib *PKCS11Lib) Model() string
- func (lib *PKCS11Lib) NewSession(slot uint) (pkcs11.SessionHandle, error)
- func (lib *PKCS11Lib) Token(slotID uint) (cryptoprov.KeyManager, error)
- func (lib *PKCS11Lib) TokensInfo() ([]*SlotTokenInfo, error)
- type PKCS11Object
- type PKCS11PrivateKey
- type PKCS11PrivateKeyECDSA
- func (priv *PKCS11PrivateKeyECDSA) Public() crypto.PublicKey
- func (priv *PKCS11PrivateKeyECDSA) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
- func (priv *PKCS11PrivateKeyECDSA) SignContext(ctx context.Context, _ io.Reader, digest []byte, _ crypto.SignerOpts) ([]byte, error)
- type PKCS11PrivateKeyMLDSA
- func (priv *PKCS11PrivateKeyMLDSA) Public() crypto.PublicKey
- func (priv *PKCS11PrivateKeyMLDSA) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) ([]byte, error)
- func (priv *PKCS11PrivateKeyMLDSA) SignContext(ctx context.Context, _ io.Reader, message []byte, opts crypto.SignerOpts) ([]byte, error)
- type PKCS11PrivateKeyRSA
- func (priv *PKCS11PrivateKeyRSA) Decrypt(rand io.Reader, ciphertext []byte, options crypto.DecrypterOpts) (plaintext []byte, err error)
- func (priv *PKCS11PrivateKeyRSA) DecryptContext(ctx context.Context, _ io.Reader, ciphertext []byte, ...) (plaintext []byte, err error)
- func (priv *PKCS11PrivateKeyRSA) Public() crypto.PublicKey
- func (priv *PKCS11PrivateKeyRSA) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error)
- func (priv *PKCS11PrivateKeyRSA) SignContext(ctx context.Context, _ io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error)
- func (priv *PKCS11PrivateKeyRSA) Validate() error
- type SlotInfo
- type SlotTokenInfo
- type TokenConfig
- type TokenInfo
Constants ¶
const DefaultMaxSessions = 1024
DefaultMaxSessions is the default limit of pooled sessions per slot of one PKCS11Lib; see WithMaxSessions.
Variables ¶
var AttributeNames = map[uint]string{ pkcs11.CKA_ID: "ID", pkcs11.CKA_LABEL: "Label", pkcs11.CKA_KEY_TYPE: "Key type", pkcs11.CKA_CLASS: "Class", }
AttributeNames maps PKCS11 attribute to string
var KeyTypeNames = map[uint]string{ pkcs11.CKK_RSA: "RSA", pkcs11.CKK_DSA: "DSA", pkcs11.CKK_DH: "DH", pkcs11.CKK_EC: "ECDSA", // contains filtered or unexported fields }
KeyTypeNames maps PKCS11 key type to string
var ObjectClassNames = map[uint]string{ pkcs11.CKO_DATA: "Data", pkcs11.CKO_CERTIFICATE: "Certificate", pkcs11.CKO_PUBLIC_KEY: "Public key", pkcs11.CKO_PRIVATE_KEY: "Private key", pkcs11.CKO_SECRET_KEY: "Secret key", }
ObjectClassNames maps PKCS11 object class to string
Functions ¶
func ConvertToPublic ¶
func ConvertToPublic(priv crypto.PrivateKey) (crypto.PublicKey, error)
ConvertToPublic converts a private key interface to crypto.PublicKey type
func LoadProvider ¶
func LoadProvider(cfg cryptoprov.TokenConfig) (cryptoprov.Provider, error)
LoadProvider provides loader for crypto11 provider
func UlongToBytes ¶
UlongToBytes encodes n as a native CK_ULONG attribute value (host byte order, ulongSize bytes). Where CK_ULONG is 32 bits, only the low 32 bits of n are kept.
Types ¶
type KeyIdentifier ¶
KeyIdentifier interface provides key ID and label
type Option ¶
type Option func(*options)
Option configures Init and ConfigureFromFile.
func WithMaxSessions ¶
WithMaxSessions limits the pooled sessions that one PKCS11Lib keeps open on each slot (default DefaultMaxSessions). When all of them are in use, an operation waits until one is returned. The login session opened by Init is not counted. n must be positive.
type PKCS11Lib ¶
type PKCS11Lib struct {
// Ctx is the shared module context. It is nil after Close.
Ctx *pkcs11.Ctx
Config TokenConfig
// Session is the login session on Slot, opened by Init and closed by
// Close. It keeps the token logged in while pooled sessions are opened
// and closed. It is replaced when the token has to be logged in again
// after a logout or a reinsertion (XPKI-110), so do not cache, close or
// use it concurrently with operations of this PKCS11Lib.
Session pkcs11.SessionHandle
Slot *SlotTokenInfo
// contains filtered or unexported fields
}
PKCS11Lib contains a reference to an open PKCS#11 slot and configuration.
Every PKCS11Lib opened on the same library path shares one loaded module: the first Init initializes it and the last Close finalizes it. Each PKCS11Lib owns its own session pools and login session. It is safe for concurrent use; after Close its operations return an error.
func ConfigureFromFile ¶
ConfigureFromFile loads a token configuration with LoadTokenConfig and opens it with Init; opts and the returned PKCS11Lib are as for Init.
func Init ¶
func Init(config TokenConfig, opts ...Option) (_ *PKCS11Lib, err error)
Init configures PKCS#11 from a TokenConfig, opens the token slot and logs in when the token requires it.
The library at config.Path() is loaded and initialized by the first PKCS11Lib that uses it and shared by later ones. On error Init releases everything it acquired. Call Close to release the returned PKCS11Lib.
func (*PKCS11Lib) Close ¶
Close releases the resources of lib. New operations fail at once, and Close waits for the operations in flight to return their sessions. It then closes the sessions of lib, including the login session, and releases the module; the last PKCS11Lib on a module calls C_Finalize (unless the module was initialized outside this package) and unloads it. Close is idempotent: every call, including concurrent ones, waits for the first to finish and returns its result.
Close must not be called from inside an operation of lib, which it would wait for forever. Sessions a caller opened with NewSession, and the *OnSession methods that use them, are not tracked: close those sessions and stop using them before Close.
func (*PKCS11Lib) CurrentSlotID ¶
CurrentSlotID returns current slot ID
func (*PKCS11Lib) DestroyKey ¶
DestroyKey destroys the private and the public key objects with CKA_ID keyID on the token lib is logged in to. One missing half is tolerated; a key with neither is a wrapped cryptoprov.ErrKeyNotFound. ctx bounds the wait for a session.
func (*PKCS11Lib) ExportKey ¶
ExportKey returns PKCS#11 URI for specified key ID. It does not return key bytes. A key the token does not have is a wrapped cryptoprov.ErrKeyNotFound. ctx bounds the wait for a session.
func (*PKCS11Lib) FindKeyPair ¶
func (lib *PKCS11Lib) FindKeyPair(ctx context.Context, keyID, label string) (crypto.PrivateKey, error)
FindKeyPair retrieves a previously created asymmetric key.
Either (but not both) of id and label may be nil, in which case they are ignored. ctx bounds the wait for a session.
func (*PKCS11Lib) FindKeyPairOnSession ¶
func (lib *PKCS11Lib) FindKeyPairOnSession(session pkcs11.SessionHandle, slot uint, keyID, label string) (crypto.PrivateKey, error)
FindKeyPairOnSession retrieves a previously created asymmetric key, using a specified session.
Either (but not both) of id and label may be nil, in which case they are ignored. session is owned by the caller; after Close it returns errClosed.
func (*PKCS11Lib) FindKeyPairOnSlot ¶
func (lib *PKCS11Lib) FindKeyPairOnSlot(ctx context.Context, slot uint, keyID, label string) (crypto.PrivateKey, error)
FindKeyPairOnSlot retrieves a previously created asymmetric key, using a specified slot.
Either (but not both) of id and label may be nil, in which case they are ignored. ctx bounds the wait for a session.
func (*PKCS11Lib) GenRandom ¶
GenRandom fills data with random bytes generated via PKCS#11 using the default slot.
func (*PKCS11Lib) GenerateECDSAKeyPair ¶
func (lib *PKCS11Lib) GenerateECDSAKeyPair(ctx context.Context, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
GenerateECDSAKeyPair creates an ECDSA private key using curve c.
The key will have a random label and ID.
Only a limited set of named elliptic curves are supported. The underlying PKCS#11 implementation may impose further restrictions.
func (*PKCS11Lib) GenerateECDSAKeyPairOnSession ¶
func (lib *PKCS11Lib) GenerateECDSAKeyPairOnSession(session pkcs11.SessionHandle, slot uint, id []byte, label []byte, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
GenerateECDSAKeyPairOnSession creates an ECDSA private key using curve c, using a specified session.
label and/or id can be nil, in which case a random values will be generated.
Only a limited set of named elliptic curves are supported. The underlying PKCS#11 implementation may impose further restrictions. session is owned by the caller; after Close it returns errClosed.
func (*PKCS11Lib) GenerateECDSAKeyPairOnSlot ¶
func (lib *PKCS11Lib) GenerateECDSAKeyPairOnSlot(ctx context.Context, slot uint, id []byte, label []byte, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
GenerateECDSAKeyPairOnSlot creates an ECDSA private key using curve c, on a specified slot.
label and/or id can be nil, in which case a random values will be generated.
Only a limited set of named elliptic curves are supported. The underlying PKCS#11 implementation may impose further restrictions. ctx bounds the wait for a session.
func (*PKCS11Lib) GenerateECDSAKeyPairWithLabel ¶
func (lib *PKCS11Lib) GenerateECDSAKeyPairWithLabel(ctx context.Context, label string, c elliptic.Curve) (*PKCS11PrivateKeyECDSA, error)
GenerateECDSAKeyPairWithLabel creates an ECDSA private key using curve c.
The key will have a random ID.
Only a limited set of named elliptic curves are supported. The underlying PKCS#11 implementation may impose further restrictions.
func (*PKCS11Lib) GenerateKey ¶
func (lib *PKCS11Lib) GenerateKey(ctx context.Context, req *cryptoprov.GenerateKeyRequest) (crypto.PrivateKey, error)
GenerateKey generates the key pair req describes on the token lib is logged in to and returns a handle that also reports its key ID and label (KeyIdentifier): an RSA key with the permissions of req.Usage (CKA_SIGN for cryptoprov.KeyUsageSign, CKA_DECRYPT for cryptoprov.KeyUsageEncrypt, or both), an ECDSA key on P-256, P-384 or P-521, or an ML-DSA key, for which the token must implement PKCS#11 v3.2 (SoftHSM 2.6 does not and fails the key pair generation). A PKCS#11 object has no tags, so req.Tags is a wrapped cryptoprov.ErrNotSupported. ctx bounds the wait for a session; a generation that has started is not interrupted.
func (*PKCS11Lib) GenerateMLDSAKeyPairOnSlot ¶
func (lib *PKCS11Lib) GenerateMLDSAKeyPairOnSlot(ctx context.Context, slot uint, id []byte, label []byte, params mldsa.Parameters) (*PKCS11PrivateKeyMLDSA, error)
GenerateMLDSAKeyPairOnSlot creates an ML-DSA key pair of params on slot with CKM_ML_DSA_KEY_PAIR_GEN, which needs a PKCS#11 v3.2 token. label and/or id can be nil, in which case random values are generated. ctx bounds the wait for a session.
func (*PKCS11Lib) GenerateMLDSAKeyPairWithLabel ¶
func (lib *PKCS11Lib) GenerateMLDSAKeyPairWithLabel(ctx context.Context, label string, params mldsa.Parameters) (*PKCS11PrivateKeyMLDSA, error)
GenerateMLDSAKeyPairWithLabel creates an ML-DSA key pair of params with label and a random ID on the configured slot.
func (*PKCS11Lib) GenerateRSAKeyPair ¶
func (lib *PKCS11Lib) GenerateRSAKeyPair(ctx context.Context, bits int, usage cryptoprov.KeyUsage) (*PKCS11PrivateKeyRSA, error)
GenerateRSAKeyPair creates an RSA private key of given length.
The key will have a random label and ID.
RSA private keys are generated with both sign and decrypt permissions, and a public exponent of 65537.
func (*PKCS11Lib) GenerateRSAKeyPairOnSession ¶
func (lib *PKCS11Lib) GenerateRSAKeyPairOnSession( session pkcs11.SessionHandle, slot uint, id []byte, label []byte, bits int, usage cryptoprov.KeyUsage, ) (*PKCS11PrivateKeyRSA, error)
GenerateRSAKeyPairOnSession creates an RSA private key of given length, on a specified session.
Either or both label and/or id can be nil, in which case a random values will be generated.
RSA private keys are generated with both sign and decrypt permissions, and a public exponent of 65537. session is owned by the caller; after Close it returns errClosed.
func (*PKCS11Lib) GenerateRSAKeyPairOnSlot ¶
func (lib *PKCS11Lib) GenerateRSAKeyPairOnSlot(ctx context.Context, slot uint, id []byte, label []byte, bits int, usage cryptoprov.KeyUsage) (*PKCS11PrivateKeyRSA, error)
GenerateRSAKeyPairOnSlot creates a RSA private key on a specified slot
Either or both label and/or id can be nil, in which case a random values will be generated. usage selects the permissions of the key: cryptoprov.KeyUsageSign is CKA_SIGN and CKA_VERIFY, cryptoprov.KeyUsageEncrypt is CKA_DECRYPT and CKA_ENCRYPT, and the permissions of a usage that was not asked for are set to false. Zero leaves all four to the token's defaults. ctx bounds the wait for a session.
func (*PKCS11Lib) GenerateRSAKeyPairWithLabel ¶
func (lib *PKCS11Lib) GenerateRSAKeyPairWithLabel(ctx context.Context, label string, bits int, usage cryptoprov.KeyUsage) (*PKCS11PrivateKeyRSA, error)
GenerateRSAKeyPairWithLabel creates an RSA private key of given length.
The key will have a random ID.
RSA private keys are generated with both sign and decrypt permissions, and a public exponent of 65537.
func (*PKCS11Lib) GetKey ¶
GetKey returns the handle of the private key with CKA_ID keyID on the token lib is logged in to. A key the token does not have is a wrapped cryptoprov.ErrKeyNotFound. ctx bounds the wait for a session.
func (*PKCS11Lib) Identify ¶
func (lib *PKCS11Lib) Identify(ctx context.Context, object *PKCS11Object) (keyID, label string, err error)
Identify returns the ID and label for a PKCS#11 object.
Either of these values may be used to retrieve the key for later use. The object's Handle is used as given; IdentifyKey, given a private key of this package, also recovers from a handle invalidated by a logout. ctx bounds the wait for a session.
func (*PKCS11Lib) IdentifyKey ¶
func (lib *PKCS11Lib) IdentifyKey(ctx context.Context, priv crypto.PrivateKey) (keyID, label string, err error)
IdentifyKey returns the ID and label for a private key. A key GenerateKey returned carries them; for any other key of this package they are read from the token, and ctx bounds the wait for a session.
func (*PKCS11Lib) KeyInfo ¶
func (lib *PKCS11Lib) KeyInfo(ctx context.Context, keyID string, fields cryptoprov.KeyFields) (*cryptoprov.KeyInfo, error)
KeyInfo describes the private key with CKA_ID keyID on the token lib is logged in to: every field of the Metadata and State groups and, with cryptoprov.KeyFieldPublicKey, the PEM public key of its pair. A key the token does not have is a wrapped cryptoprov.ErrKeyNotFound. ctx bounds the wait for a session.
func (*PKCS11Lib) ListKeys ¶
func (lib *PKCS11Lib) ListKeys(ctx context.Context, req *cryptoprov.ListKeysRequest) (*cryptoprov.ListKeysResponse, error)
ListKeys returns one page of the private keys of the token lib is logged in to.
The filter becomes the C_FindObjectsInit template where it can: the private key class, CKA_KEY_TYPE for one type, CKA_LABEL for the exact label, and CKA_SIGN or, for RSA keys, CKA_DECRYPT for one usage. A label prefix, several types and a usage of either kind are checked on the attributes of each candidate, at most a page of candidates per call. The usage is what the token says: CKA_SIGN, and CKA_DECRYPT of an RSA key. A key GenerateKey created has only the usage it was asked for; a key created without one of the attributes has the token's default, which is true for both on SoftHSM. A PKCS#11 object has no tags, so a filter on tags is a wrapped cryptoprov.ErrNotSupported, and it has no state: every key is enabled.
The page token is the offset in the search order of the token, so a key created or destroyed between two pages can be repeated or missed. Attributes are read for the keys of the page only: ID, label, type and class always, and usage and size with cryptoprov.KeyFieldMetadata. ctx is checked between the batches of the search and between keys; a PKCS#11 call that has started is not interrupted.
It uses its own read-only session rather than a pooled RW one, so a write-protected token can still be listed. Private keys are visible only to a logged-in session, and a logged-out token lists none without an error, so the session state is checked first and the token is logged in again when needed (XPKI-110).
func (*PKCS11Lib) ListTokens ¶
ListTokens returns the tokens of the PKCS#11 module that have a serial number or a label; Current marks the one lib is logged in to.
func (*PKCS11Lib) Manufacturer ¶
Manufacturer returns manufacturer for the calling library
func (*PKCS11Lib) NewSession ¶
func (lib *PKCS11Lib) NewSession(slot uint) (pkcs11.SessionHandle, error)
NewSession opens a new RW session on slot. The caller owns the session and must close it with Ctx.CloseSession before Close is called.
func (*PKCS11Lib) Token ¶
func (lib *PKCS11Lib) Token(slotID uint) (cryptoprov.KeyManager, error)
Token returns the KeyManager of the token in slot slotID. Only the token lib is logged in to shows its private keys and is logged in again after a logout (XPKI-110); on another slot the manager sees what the token gives a public session. It fails after Close.
func (*PKCS11Lib) TokensInfo ¶
func (lib *PKCS11Lib) TokensInfo() ([]*SlotTokenInfo, error)
TokensInfo returns list of tokens
type PKCS11Object ¶
type PKCS11Object struct {
// The PKCS#11 slot number.
//
// This is used internally to find a session handle that can
// access this object.
Slot uint
// contains filtered or unexported fields
}
PKCS11Object contains a reference to a loaded PKCS#11 object.
func (*PKCS11Object) Handle ¶
func (o *PKCS11Object) Handle() pkcs11.ObjectHandle
Handle returns the PKCS#11 object handle of the object as it is now. A logout, or a token removal, invalidates the handles of private objects; the keys this package returns remember their CKA_ID and look their object up again when an operation finds the handle stale, and Handle follows that refresh (XPKI-110). It does not check the handle against the token: after a logout it is the stale one until the next operation on the key. An object without a CKA_ID keeps the handle it was found with.
type PKCS11PrivateKey ¶
type PKCS11PrivateKey struct {
PKCS11Object
// The corresponding public key
PubKey crypto.PublicKey
}
PKCS11PrivateKey contains a reference to a loaded PKCS#11 private key object.
func (PKCS11PrivateKey) Public ¶
func (p PKCS11PrivateKey) Public() crypto.PublicKey
Public returns the public half of a private key.
This partially implements the go.crypto.Signer and go.crypto.Decrypter interfaces for PKCS11PrivateKey. (The remains of the implementation is in the key-specific types.)
type PKCS11PrivateKeyECDSA ¶
type PKCS11PrivateKeyECDSA struct {
// contains filtered or unexported fields
}
PKCS11PrivateKeyECDSA contains a reference to a loaded PKCS#11 ECDSA private key object.
func (*PKCS11PrivateKeyECDSA) Public ¶
func (priv *PKCS11PrivateKeyECDSA) Public() crypto.PublicKey
Public returns the public half of a private key.
This partially implements the go.crypto.Signer and go.crypto.Decrypter interfaces for PKCS11PrivateKey. (The remains of the implementation is in the key-specific types.)
func (*PKCS11PrivateKeyECDSA) Sign ¶
func (priv *PKCS11PrivateKeyECDSA) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
Sign signs a message using an ECDSA key.
This completes the implementation of crypto.Signer for PKCS11PrivateKeyECDSA.
PKCS#11 expects to pick its own random data where necessary for signatures, so the rand argument is ignored.
The return value is a DER-encoded byteblock. Sign is SignContext with context.Background().
func (*PKCS11PrivateKeyECDSA) SignContext ¶ added in v2.0.328
func (priv *PKCS11PrivateKeyECDSA) SignContext(ctx context.Context, _ io.Reader, digest []byte, _ crypto.SignerOpts) ([]byte, error)
SignContext is Sign with ctx bounding the wait for a pooled session (cryptoprov.ContextSigner).
type PKCS11PrivateKeyMLDSA ¶
type PKCS11PrivateKeyMLDSA struct {
// contains filtered or unexported fields
}
PKCS11PrivateKeyMLDSA contains a reference to a loaded PKCS#11 ML-DSA private key object. It signs messages, not digests (crypto/x509 passes the whole TBS with a zero hash); see Sign.
func (*PKCS11PrivateKeyMLDSA) Public ¶
func (priv *PKCS11PrivateKeyMLDSA) Public() crypto.PublicKey
Public returns the public half of the key, an *mldsa.PublicKey.
func (*PKCS11PrivateKeyMLDSA) Sign ¶
func (priv *PKCS11PrivateKeyMLDSA) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) ([]byte, error)
Sign signs message with the ML-DSA key through CKM_ML_DSA and returns the FIPS 204 signature. It accepts the message with nil options, a zero hash or an *mldsa.Options without context (cryptoprov.MLDSASignerOptions); the token hedges the signature. A digest hash, a μ (crypto.MLDSAMu) and a context string are errors, since PKCS#11 v3.2 has no external-μ mechanism and this package passes no mechanism parameter. PKCS#11 picks its own randomness, so rand is ignored. Sign is SignContext with context.Background().
func (*PKCS11PrivateKeyMLDSA) SignContext ¶ added in v2.0.328
func (priv *PKCS11PrivateKeyMLDSA) SignContext(ctx context.Context, _ io.Reader, message []byte, opts crypto.SignerOpts) ([]byte, error)
SignContext is Sign with ctx bounding the wait for a pooled session (cryptoprov.ContextSigner).
type PKCS11PrivateKeyRSA ¶
type PKCS11PrivateKeyRSA struct {
// contains filtered or unexported fields
}
PKCS11PrivateKeyRSA contains a reference to a loaded PKCS#11 RSA private key object.
func (*PKCS11PrivateKeyRSA) Decrypt ¶
func (priv *PKCS11PrivateKeyRSA) Decrypt(rand io.Reader, ciphertext []byte, options crypto.DecrypterOpts) (plaintext []byte, err error)
Decrypt decrypt a message using a RSA key.
This completes the implementation of crypto.Decrypter for PKCS11PrivateKeyRSA.
If options is nil or a *rsa.PKCS1v15DecryptOptions, PKCS#1 v1.5 decryption is performed; a non-zero SessionKeyLen is not supported. If options is a *rsa.OAEPOptions, OAEP decryption is performed.
The underlying PKCS#11 implementation may impose further restrictions. Decrypt is DecryptContext with context.Background().
func (*PKCS11PrivateKeyRSA) DecryptContext ¶ added in v2.0.328
func (priv *PKCS11PrivateKeyRSA) DecryptContext(ctx context.Context, _ io.Reader, ciphertext []byte, options crypto.DecrypterOpts) (plaintext []byte, err error)
DecryptContext is Decrypt with ctx bounding the wait for a pooled session (cryptoprov.ContextDecrypter).
func (*PKCS11PrivateKeyRSA) Public ¶
func (priv *PKCS11PrivateKeyRSA) Public() crypto.PublicKey
Public returns the public half of a private key.
This partially implements the go.crypto.Signer and go.crypto.Decrypter interfaces for PKCS11PrivateKey. (The remains of the implementation is in the key-specific types.)
func (*PKCS11PrivateKeyRSA) Sign ¶
func (priv *PKCS11PrivateKeyRSA) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error)
Sign signs a message using a RSA key.
This completes the implementation of crypto.Signer for PKCS11PrivateKeyRSA.
PKCS#11 expects to pick its own random data where necessary for signatures, so the rand argument is ignored.
For PSS, rsa.PSSSaltLengthAuto uses the largest salt the key allows, rsa.PSSSaltLengthEqualsHash uses the hash length, and a positive value is used as-is. For PKCS#1 v1.5 the hash must be one of SHA-1, SHA-224, SHA-256, SHA-384 or SHA-512; other hashes are rejected. The underlying PKCS#11 implementation may impose further restrictions. Sign is SignContext with context.Background().
func (*PKCS11PrivateKeyRSA) SignContext ¶ added in v2.0.328
func (priv *PKCS11PrivateKeyRSA) SignContext(ctx context.Context, _ io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error)
SignContext is Sign with ctx bounding the wait for a pooled session (cryptoprov.ContextSigner).
func (*PKCS11PrivateKeyRSA) Validate ¶
func (priv *PKCS11PrivateKeyRSA) Validate() error
Validate checks an RSA key.
Since the private key material is not normally available only very limited validation is possible. (The underlying PKCS#11 implementation may perform stricter checking.)
type SlotTokenInfo ¶
type SlotTokenInfo struct {
// contains filtered or unexported fields
}
SlotTokenInfo provides info about Token on slot
func (*SlotTokenInfo) Description ¶
func (s *SlotTokenInfo) Description() string
Description of the slot
func (*SlotTokenInfo) Manufacturer ¶
func (s *SlotTokenInfo) Manufacturer() string
Manufacturer of the token
func (*SlotTokenInfo) SerialNumber ¶
func (s *SlotTokenInfo) SerialNumber() string
SerialNumber of the token
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; empty matches any serial
TokenSerial() string
// Token label; empty matches any 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.
Init selects the token by the configured serial number and label: empty fields are ignored, so a token must match every nonempty one, and at least one of them is required. If several tokens match, the first slot wins.
Supply this to Init, or alternatively use ConfigureFromFile.
func LoadTokenConfig ¶
func LoadTokenConfig(filename string) (TokenConfig, error)
LoadTokenConfig loads PKCS#11 token configuration