crypto11

package
v0.19.156 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: Apache-2.0, MIT Imports: 24 Imported by: 2

Documentation

Overview

Package crypto11 allows for access cryptographic keys from PKCS#11 using Go crypto API.

For simple use:

1. Either write a configuration file (see ConfigureFromFile) or define a configuration in your application (see TokenConfig and Configure). This will identify the PKCS#11 library and token to use, and contain the password (or "PIN" in PKCS#11 terminology) to use if the token requires login.

2. Create keys with GenerateDSAKeyPair, GenerateRSAKeyPair and GenerateECDSAKeyPair. The keys you get back implement the standard Go crypto.Signer interface (and crypto.Decrypter, for RSA). They are automatically persisted under random a randomly generated label and ID (use the Identify method to discover them).

3. Retrieve existing keys with FindKeyPair. The return value is a Go crypto.PrivateKey; it may be converted either to crypto.Signer or to *PKCS11PrivateKeyDSA, *PKCS11PrivateKeyECDSA or *PKCS11PrivateKeyRSA.

Sessions and concurrency:

Note that PKCS#11 session handles must not be used concurrently from multiple threads. Consumers of the Signer interface know nothing of this and expect to be able to sign from multiple threads without constraint. We address this as follows.

1. PKCS11Object captures both the object handle and the slot ID for an object.

2. For each slot we maintain a pool of read-write sessions. The pool expands dynamically up to an (undocumented) limit.

3. Each operation transiently takes a session from the pool. They have exclusive use of the session, meeting PKCS#11's concurrency requirements.

The details are, partially, exposed in the API; since the target use case is PKCS#11-unaware operation it may be that the API as it stands isn't good enough for PKCS#11-aware applications. Feedback welcome.

See also https://golang.org/pkg/crypto/

Index

Constants

This section is empty.

Variables

View Source
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 atribute to string

View Source
var KeyTypeNames = map[uint]string{
	pkcs11.CKK_RSA:   "RSA",
	pkcs11.CKK_DSA:   "DSA",
	pkcs11.CKK_DH:    "DH",
	pkcs11.CKK_ECDSA: "ECDSA",
}

KeyTypeNames maps PKCS11 key type to string

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

func BytesToUlong(bs []byte) (n uint)

BytesToUlong converts []byte to Ulong

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

func UlongToBytes(n uint) []byte

UlongToBytes converts Ulong to []byte

Types

type KeyIdentifier

type KeyIdentifier interface {
	KeyID() string
	Label() string
}

KeyIdentifier interface provides key ID and label

type KeyPurpose

type KeyPurpose int

KeyPurpose declares the purpose for keys

const (
	// Undefined purpose of key
	Undefined KeyPurpose = 0
	// Signing specifies the purpose of key to be used in signing/verification operations
	Signing KeyPurpose = 1
	// Encryption specifies the purpose of key to be used in encryption/decryption operations
	Encryption KeyPurpose = 2
)

type PKCS11Lib

type PKCS11Lib struct {
	Ctx     *pkcs11.Ctx
	Config  TokenConfig
	Session pkcs11.SessionHandle
	Slot    *SlotTokenInfo
	// contains filtered or unexported fields
}

PKCS11Lib contains a reference to an open PKCS#11 slot and configuration

func ConfigureFromFile

func ConfigureFromFile(configLocation string) (*PKCS11Lib, error)

ConfigureFromFile configures PKCS#11 from a name configuration file.

Configuration files are a JSON representation of the PKCSConfig object. The return value is as for Configure().

Note that if CRYPTO11_CONFIG_PATH is set in the environment, configuration will be read from that file, overriding any later runtime configuration.

func Init

func Init(config TokenConfig) (*PKCS11Lib, error)

Init configures PKCS#11 from a TokenConfig, and opens default slot

func (*PKCS11Lib) Close

func (lib *PKCS11Lib) Close()

Close releases allocated resources

func (*PKCS11Lib) CurrentSlotID

func (lib *PKCS11Lib) CurrentSlotID() uint

CurrentSlotID returns current slot ID

func (*PKCS11Lib) DestroyKeyPairOnSlot

func (lib *PKCS11Lib) DestroyKeyPairOnSlot(slotID uint, keyID string) error

DestroyKeyPairOnSlot destroys key pair

func (*PKCS11Lib) EnumKeys

func (lib *PKCS11Lib) EnumKeys(slotID uint, prefix string) ([]cryptoprov.KeyInfo, error)

EnumKeys returns lists of keys on the slot

func (*PKCS11Lib) EnumTokens

func (lib *PKCS11Lib) EnumTokens(currentSlotOnly bool) ([]cryptoprov.TokenInfo, error)

EnumTokens enumerates tokens

func (*PKCS11Lib) ExportKey

func (lib *PKCS11Lib) ExportKey(keyID string) (string, []byte, error)

ExportKey returns PKCS#11 URI for specified key ID. It does not return key bytes.

func (*PKCS11Lib) FindKeyPair

func (lib *PKCS11Lib) FindKeyPair(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.

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.

func (*PKCS11Lib) FindKeyPairOnSlot

func (lib *PKCS11Lib) FindKeyPairOnSlot(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.

func (*PKCS11Lib) FindKeys

func (lib *PKCS11Lib) FindKeys(session pkcs11.SessionHandle, keylabel string, keyclass uint, keytype uint) ([]pkcs11.ObjectHandle, error)

FindKeys returns key objects on the slot matching label and key type

func (*PKCS11Lib) GenRandom

func (lib *PKCS11Lib) GenRandom(data []byte) (n int, err error)

GenRandom fills data with random bytes generated via PKCS#11 using the default slot.

func (*PKCS11Lib) GenerateDSAKeyPair

func (lib *PKCS11Lib) GenerateDSAKeyPair(params *dsa.Parameters) (*PKCS11PrivateKeyDSA, error)

GenerateDSAKeyPair creates a DSA private key on the default slot

The key will have a random label and ID.

func (*PKCS11Lib) GenerateDSAKeyPairOnSession

func (lib *PKCS11Lib) GenerateDSAKeyPairOnSession(session pkcs11.SessionHandle, slot uint, id []byte, label []byte, params *dsa.Parameters) (*PKCS11PrivateKeyDSA, error)

GenerateDSAKeyPairOnSession creates a DSA private key using a specified session

Either or both label and/or id can be nil, in which case a random values will be generated.

func (*PKCS11Lib) GenerateDSAKeyPairOnSlot

func (lib *PKCS11Lib) GenerateDSAKeyPairOnSlot(slot uint, id []byte, label []byte, params *dsa.Parameters) (*PKCS11PrivateKeyDSA, error)

GenerateDSAKeyPairOnSlot creates a DSA 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.

func (*PKCS11Lib) GenerateECDSAKey

func (lib *PKCS11Lib) GenerateECDSAKey(label string, curve elliptic.Curve) (crypto.PrivateKey, error)

GenerateECDSAKey generates ECDSA key pair

func (*PKCS11Lib) GenerateECDSAKeyPair

func (lib *PKCS11Lib) GenerateECDSAKeyPair(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.

func (*PKCS11Lib) GenerateECDSAKeyPairOnSlot

func (lib *PKCS11Lib) GenerateECDSAKeyPairOnSlot(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.

func (*PKCS11Lib) GenerateECDSAKeyPairWithLabel

func (lib *PKCS11Lib) GenerateECDSAKeyPairWithLabel(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) GenerateRSAKey

func (lib *PKCS11Lib) GenerateRSAKey(label string, bits int, purpose int) (crypto.PrivateKey, error)

GenerateRSAKey generates RSA key pair

func (*PKCS11Lib) GenerateRSAKeyPair

func (lib *PKCS11Lib) GenerateRSAKeyPair(bits int, purpose KeyPurpose) (*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,
	purpose KeyPurpose,
) (*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.

func (*PKCS11Lib) GenerateRSAKeyPairOnSlot

func (lib *PKCS11Lib) GenerateRSAKeyPairOnSlot(slot uint, id []byte, label []byte, bits int, purpose KeyPurpose) (*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.

func (*PKCS11Lib) GenerateRSAKeyPairWithLabel

func (lib *PKCS11Lib) GenerateRSAKeyPairWithLabel(label string, bits int, purpose KeyPurpose) (*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

func (lib *PKCS11Lib) GetKey(keyID string) (crypto.PrivateKey, error)

GetKey returns private key handle

func (*PKCS11Lib) Identify

func (lib *PKCS11Lib) Identify(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.

func (*PKCS11Lib) IdentifyKey

func (lib *PKCS11Lib) IdentifyKey(priv crypto.PrivateKey) (keyID, label string, err error)

IdentifyKey returns the ID and label for a private key.

func (*PKCS11Lib) KeyInfo

func (lib *PKCS11Lib) KeyInfo(slotID uint, keyID string, includePublic bool) (*cryptoprov.KeyInfo, error)

KeyInfo retrieves info about key with the specified id

func (*PKCS11Lib) ListKeys

func (lib *PKCS11Lib) ListKeys(session pkcs11.SessionHandle, keyclass uint, keytype uint) ([]pkcs11.ObjectHandle, error)

ListKeys returns key objects on the slot matching the key class and type

func (*PKCS11Lib) Manufacturer

func (lib *PKCS11Lib) Manufacturer() string

Manufacturer returns manufacturer for the calling library

func (*PKCS11Lib) Model

func (lib *PKCS11Lib) Model() string

Model returns model for the calling library

func (*PKCS11Lib) NewSession

func (lib *PKCS11Lib) NewSession(slot uint) (pkcs11.SessionHandle, error)

NewSession creates new RW session for a given slot

func (*PKCS11Lib) TokensInfo

func (lib *PKCS11Lib) TokensInfo() ([]*SlotTokenInfo, error)

TokensInfo returns list of tokens

type PKCS11Object

type PKCS11Object struct {
	// The PKCS#11 object handle.
	Handle pkcs11.ObjectHandle

	// The PKCS#11 slot number.
	//
	// This is used internally to find a session handle that can
	// access this object.
	Slot uint
}

PKCS11Object contains a reference to a loaded PKCS#11 object.

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 PKCS11PrivateKeyDSA

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

PKCS11PrivateKeyDSA contains a reference to a loaded PKCS#11 DSA private key object.

func (*PKCS11PrivateKeyDSA) Public

func (priv *PKCS11PrivateKeyDSA) 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 (*PKCS11PrivateKeyDSA) Sign

func (priv *PKCS11PrivateKeyDSA) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error)

Sign signs a message using a DSA key.

This completes the implemention of crypto.Signer for PKCS11PrivateKeyDSA.

PKCS#11 expects to pick its own random data for signatures, so the rand argument is ignored.

The return value is a DER-encoded byteblock.

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 implemention 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.

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 implemention of crypto.Decrypter for PKCS11PrivateKeyRSA.

Note that the SessionKeyLen option (for PKCS#1v1.5 decryption) is not supported.

The underlying PKCS#11 implementation may impose further restrictions.

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 implemention of crypto.Signer for PKCS11PrivateKeyRSA.

PKCS#11 expects to pick its own random data where necessary for signatures, so the rand argument is ignored.

Note that (at present) the crypto.rsa.PSSSaltLengthAuto option is not supported. The caller must either use crypto.rsa.PSSSaltLengthEqualsHash (recommended) or pass an explicit salt length. Moreover the underlying PKCS#11 implementation may impose further restrictions.

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 SlotInfo

type SlotInfo pkcs11.SlotInfo

SlotInfo provides information about a slot.

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) Label

func (s *SlotTokenInfo) Label() string

Label of the token

func (*SlotTokenInfo) Manufacturer

func (s *SlotTokenInfo) Manufacturer() string

Manufacturer of the token

func (*SlotTokenInfo) Model

func (s *SlotTokenInfo) Model() string

Model of the token

func (*SlotTokenInfo) SerialNumber

func (s *SlotTokenInfo) SerialNumber() string

SerialNumber of the token

func (*SlotTokenInfo) SlotID

func (s *SlotTokenInfo) SlotID() uint

SlotID is ID of the slot

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 either by serial number or label. If both are specified then the first match wins.

Supply this to Configure(), or alternatively use ConfigureFromFile().

func LoadTokenConfig

func LoadTokenConfig(filename string) (TokenConfig, error)

LoadTokenConfig loads PKCS#11 token configuration

type TokenInfo

type TokenInfo pkcs11.TokenInfo

TokenInfo provides information about a token.

Jump to

Keyboard shortcuts

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