API documentation

class PyKCS11.AES_CTR_Mechanism(counterBits, counterBlock)[source]

CKM_AES_CTR encryption mechanism

Parameters:
  • counterBits – the number of incremented bits in the counter block

  • counterBlock – a 16-byte initial value of the counter block

to_native()[source]
class PyKCS11.AES_GCM_Mechanism(iv, aad, tagBits)[source]

CKM_AES_GCM warpping mechanism

Parameters:
  • iv – initialization vector

  • aad – additional authentication data

  • tagBits – length of authentication tag in bits

to_native()[source]
class PyKCS11.CK_INFO[source]

matches the PKCS#11 CK_INFO structure

Variables:
  • cryptokiVersion – Cryptoki interface version

  • manufacturerID – blank padded

  • flags – must be zero

  • libraryDescription – blank padded

  • libraryVersion – 2 elements list

fields = {'cryptokiVersion': 'pair', 'flags': 'flags', 'libraryDescription': 'text', 'libraryVersion': 'pair', 'manufacturerID': 'text'}
class PyKCS11.CK_MECHANISM_INFO[source]

matches the PKCS#11 CK_MECHANISM_INFO structure

Variables:
  • ulMinKeySize – minimum size of the key

  • ulMaxKeySize – maximum size of the key

  • flags – bit flags specifying mechanism capabilities

fields = {'flags': 'flags', 'ulMaxKeySize': 'text', 'ulMinKeySize': 'text'}
flags_dict = {1: 'CKF_HW', 256: 'CKF_ENCRYPT', 512: 'CKF_DECRYPT', 1024: 'CKF_DIGEST', 2048: 'CKF_SIGN', 4096: 'CKF_SIGN_RECOVER', 8192: 'CKF_VERIFY', 16384: 'CKF_VERIFY_RECOVER', 32768: 'CKF_GENERATE', 65536: 'CKF_GENERATE_KEY_PAIR', 131072: 'CKF_WRAP', 262144: 'CKF_UNWRAP', 524288: 'CKF_DERIVE', 2147483648: 'CKF_EXTENSION'}
class PyKCS11.CK_OBJECT_HANDLE(session)[source]

add a __repr__() method to the LowLevel equivalent

to_dict()[source]

convert the fields of the object into a dictionnary

class PyKCS11.CK_SESSION_INFO[source]

matches the PKCS#11 CK_SESSION_INFO structure

Variables:
  • slotID – ID of the slot that interfaces with the token

  • state – state of the session

  • flags – bit flags that define the type of session

  • ulDeviceError – an error code defined by the cryptographic token

fields = {'flags': 'flags', 'slotID': 'text', 'state': 'text', 'ulDeviceError': 'text'}
flags_dict = {2: 'CKF_RW_SESSION', 4: 'CKF_SERIAL_SESSION'}
state2text()[source]

parse the self.state field and return a CKS_* string corresponding to the state

Returns:

a string

Return type:

string

class PyKCS11.CK_SLOT_INFO[source]

matches the PKCS#11 CK_SLOT_INFO structure

Variables:
  • slotDescription – blank padded

  • manufacturerID – blank padded

  • flags – See CkClass.flags2text()

  • hardwareVersion – 2 elements list

  • firmwareVersion – 2 elements list

fields = {'firmwareVersion': 'text', 'flags': 'flags', 'hardwareVersion': 'text', 'manufacturerID': 'text', 'slotDescription': 'text'}
flags_dict = {1: 'CKF_TOKEN_PRESENT', 2: 'CKF_REMOVABLE_DEVICE', 4: 'CKF_HW_SLOT'}
class PyKCS11.CK_TOKEN_INFO[source]

matches the PKCS#11 CK_TOKEN_INFO structure

Variables:
  • label – blank padded

  • manufacturerID – blank padded

  • model – string blank padded

  • serialNumber – string blank padded

  • flags

  • ulMaxSessionCount

  • ulSessionCount

  • ulMaxRwSessionCount

  • ulRwSessionCount

  • ulMaxPinLen

  • ulMinPinLen

  • ulTotalPublicMemory

  • ulFreePublicMemory

  • ulTotalPrivateMemory

  • ulFreePrivateMemory

  • hardwareVersion – 2 elements list

  • firmwareVersion – 2 elements list

  • utcTime – string

fields = {'firmwareVersion': 'pair', 'flags': 'flags', 'hardwareVersion': 'pair', 'label': 'text', 'manufacturerID': 'text', 'model': 'text', 'serialNumber': 'text', 'ulFreePrivateMemory': 'text', 'ulFreePublicMemory': 'text', 'ulMaxPinLen': 'text', 'ulMaxRwSessionCount': 'text', 'ulMaxSessionCount': 'text', 'ulMinPinLen': 'text', 'ulRwSessionCount': 'text', 'ulSessionCount': 'text', 'ulTotalPrivateMemory': 'text', 'ulTotalPublicMemory': 'text', 'utcTime': 'text'}
flags_dict = {1: 'CKF_RNG', 2: 'CKF_WRITE_PROTECTED', 4: 'CKF_LOGIN_REQUIRED', 8: 'CKF_USER_PIN_INITIALIZED', 32: 'CKF_RESTORE_KEY_NOT_NEEDED', 64: 'CKF_CLOCK_ON_TOKEN', 256: 'CKF_PROTECTED_AUTHENTICATION_PATH', 512: 'CKF_DUAL_CRYPTO_OPERATIONS', 1024: 'CKF_TOKEN_INITIALIZED', 2048: 'CKF_SECONDARY_AUTHENTICATION', 65536: 'CKF_USER_PIN_COUNT_LOW', 131072: 'CKF_USER_PIN_FINAL_TRY', 262144: 'CKF_USER_PIN_LOCKED', 524288: 'CKF_USER_PIN_TO_BE_CHANGED', 1048576: 'CKF_SO_PIN_COUNT_LOW', 2097152: 'CKF_SO_PIN_FINAL_TRY', 4194304: 'CKF_SO_PIN_LOCKED', 8388608: 'CKF_SO_PIN_TO_BE_CHANGED'}
class PyKCS11.CONCATENATE_BASE_AND_DATA_Mechanism(data)[source]

CKM_CONCATENATE_BASE_AND_DATA key derivation mechanism

Parameters:

data – a byte array to concatenate the key with

class PyKCS11.CONCATENATE_BASE_AND_KEY_Mechanism(encKey)[source]

CKM_CONCATENATE_BASE_AND_KEY key derivation mechanism

Parameters:

encKey – a handle of encryption key

to_native()[source]
class PyKCS11.CONCATENATE_DATA_AND_BASE_Mechanism(data)[source]

CKM_CONCATENATE_DATA_AND_BASE key derivation mechanism

Parameters:

data – a byte array to concatenate the key with

class PyKCS11.CkClass[source]

Base class for CK_* classes

fields = {}
flags = 0
flags2text()[source]

parse the self.flags field and create a list of CKF_* strings corresponding to bits set in flags

Returns:

a list of strings

Return type:

list

flags_dict = {}
to_dict()[source]

convert the fields of the object into a dictionnary

class PyKCS11.DigestSession(lib, session, mecha)[source]
digestKey(handle)[source]

C_DigestKey

Parameters:

handle (CK_OBJECT_HANDLE) – key handle

final()[source]

C_DigestFinal

Returns:

the digest

Return type:

ckbytelist

update(data)[source]

C_DigestUpdate

Parameters:

data (bytes or string) – data to add to the digest

class PyKCS11.ECDH1_DERIVE_Mechanism(publicData, kdf=1, sharedData=None)[source]

CKM_ECDH1_DERIVE key derivation mechanism

Parameters:
  • publicData – Other party public key which is EC Point [PC || coord-x || coord-y].

  • kdf – Key derivation function. OPTIONAL. Defaults to CKD_NULL

  • sharedData – additional shared data. OPTIONAL

to_native()[source]
class PyKCS11.KEY_DERIVATION_STRING_DATA_MechanismBase(data, mechType)[source]

Base class for mechanisms using derivation string data

Parameters:
  • data – a byte array to concatenate the key with

  • mechType – mechanism type

to_native()[source]
class PyKCS11.Mechanism(mechanism, param=None)[source]

Wraps CK_MECHANISM

Parameters:
  • mechanism (integer, any CKM_* value) – the mechanism to be used

  • param (string or list/tuple of bytes) – data to be used as crypto operation parameter (i.e. the IV for some algorithms)

See:

Session.decrypt(), Session.sign()

to_native()[source]
exception PyKCS11.PyKCS11Error(value, text='')[source]

define the possible PyKCS11 exceptions

class PyKCS11.PyKCS11Lib[source]

high level PKCS#11 binding

closeAllSessions(slot)[source]

C_CloseAllSessions

Parameters:

slot (integer) – slot number

getInfo()[source]

C_GetInfo

Returns:

a CK_INFO object

getMechanismInfo(slot, type)[source]

C_GetMechanismInfo

Parameters:
  • slot (integer) – slot number returned by getSlotList()

  • type (integer) – a CKM_* type

Returns:

information about a mechanism

Return type:

a CK_MECHANISM_INFO object

getMechanismList(slot)[source]

C_GetMechanismList

Parameters:

slot (integer) – slot number returned by getSlotList()

Returns:

the list of available mechanisms for a slot

Return type:

list

getSlotInfo(slot)[source]

C_GetSlotInfo

Parameters:

slot (integer) – slot number returned by getSlotList()

Returns:

a CK_SLOT_INFO object

getSlotList(tokenPresent=False)[source]

C_GetSlotList

Parameters:

tokenPresent (bool) – False (default) to list all slots, True to list only slots with present tokens

Returns:

a list of available slots

Return type:

list

getTokenInfo(slot)[source]

C_GetTokenInfo

Parameters:

slot (integer) – slot number returned by getSlotList()

Returns:

a CK_TOKEN_INFO object

initToken(slot, pin, label)[source]

C_InitToken

Parameters:
  • slot (integer) – slot number returned by getSlotList()

  • pin – Security Officer’s initial PIN

  • label – new label of the token

load(pkcs11dll_filename=None, *init_string)[source]

load a PKCS#11 library

Parameters:

pkcs11dll_filename (string) – the library name. If this parameter is not set then the environment variable PYKCS11LIB is used instead

Returns:

a PyKCS11Lib object

Raises:

PyKCS11Error (-1): when the load fails

openSession(slot, flags=0)[source]

C_OpenSession

Parameters:
  • slot (integer) – slot number returned by getSlotList()

  • flags (integer) – 0 (default), CKF_RW_SESSION for RW session

Returns:

a Session object

unload()[source]

unload the current instance of a PKCS#11 library

waitForSlotEvent(flags=0)[source]

C_WaitForSlotEvent

Parameters:

flags (integer) – 0 (default) or CKF_DONT_BLOCK

Returns:

slot

Return type:

integer

class PyKCS11.RSAOAEPMechanism(hashAlg, mgf, label=None)[source]

RSA OAEP Wrapping mechanism

Parameters:
  • hashAlg – the hash algorithm to use (like CKM_SHA256)

  • mgf – the mask generation function to use (like CKG_MGF1_SHA256)

  • label – the (optional) label to use

to_native()[source]
class PyKCS11.RSA_PSS_Mechanism(mecha, hashAlg, mgf, sLen)[source]

RSA PSS Wrapping mechanism

Parameters:
  • mecha – the mechanism to use (like CKM_SHA384_RSA_PKCS_PSS)

  • hashAlg – the hash algorithm to use (like CKM_SHA384)

  • mgf – the mask generation function to use (like CKG_MGF1_SHA384)

  • sLen – length, in bytes, of the salt value used in the PSS encoding (like 0 or the message length)

to_native()[source]
class PyKCS11.Session(pykcs11, session)[source]

Manage PyKCS11Lib.openSession() objects

Parameters:
  • pykcs11 (PyKCS11Lib) – PyKCS11 library object

  • session (instance of CK_SESSION_HANDLE) – session handle

closeSession()[source]

C_CloseSession

createObject(template)[source]

C_CreateObject

Parameters:

template – object template

decrypt(key, data, mecha=<PyKCS11.Mechanism object>)[source]

C_DecryptInit/C_Decrypt

Parameters:
  • key (integer) – a key handle, obtained calling findObjects().

  • data ((binary) string or list/tuple of bytes) – the data to be decrypted

  • mecha (Mechanism instance or MechanismRSAPKCS1 for CKM_RSA_PKCS) – the decrypt mechanism to be used

Returns:

the decrypted data

Return type:

list of bytes

Note:

the returned value is an instance of ckbytelist. You can easly convert it to a binary string with: bytes(ckbytelistData) or, for Python 2: ''.join(chr(i) for i in ckbytelistData)

deriveKey(baseKey, template, mecha)[source]

C_DeriveKey

Parameters:
  • baseKey (integer) – the base key handle

  • template – template for the unwrapped key

  • mecha (Mechanism) – the decrypt mechanism to be used (use ECDH1_DERIVE_Mechanism(…) for CKM_ECDH1_DERIVE)

Returns:

the unwrapped key object

Return type:

integer

destroyObject(obj)[source]

C_DestroyObject

Parameters:

obj – object ID

digest(data, mecha=<PyKCS11.Mechanism object>)[source]

C_DigestInit/C_Digest

Parameters:
  • data ((binary) sring or list/tuple of bytes) – the data to be digested

  • mecha (Mechanism) – the digesting mechanism to be used (use MechanismSHA1 for CKM_SHA_1)

Returns:

the computed digest

Return type:

list of bytes

Note:

the returned value is an istance of ckbytelist. You can easly convert it to a binary string with: bytes(ckbytelistDigest) or, for Python 2: ''.join(chr(i) for i in ckbytelistDigest)

digestSession(mecha=<PyKCS11.Mechanism object>)[source]

C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal

Parameters:

mecha (Mechanism) – the digesting mechanism to be used (use MechanismSHA1 for CKM_SHA_1)

Returns:

A DigestSession object

Return type:

DigestSession

encrypt(key, data, mecha=<PyKCS11.Mechanism object>)[source]

C_EncryptInit/C_Encrypt

Parameters:
  • key (integer) – a key handle, obtained calling findObjects().

  • data ((binary) string or list/tuple of bytes) – the data to be encrypted

  • mecha (Mechanism) – the encryption mechanism to be used (use MechanismRSAPKCS1 for CKM_RSA_PKCS)

Returns:

the encrypted data

Return type:

list of bytes

Note:

the returned value is an instance of ckbytelist. You can easly convert it to a binary string with: bytes(ckbytelistEncrypted) or, for Python 2: ''.join(chr(i) for i in ckbytelistEncrypted)

findObjects(template=())[source]

find the objects matching the template pattern

Parameters:

template (list) – list of attributes tuples (attribute,value). The default value is () and all the objects are returned

Returns:

a list of object ids

Return type:

list

generateKey(template, mecha=<PyKCS11.Mechanism object>)[source]

generate a secret key

Parameters:
  • template – template for the secret key

  • mecha – mechanism to use

Returns:

handle of the generated key

Return type:

PyKCS11.LowLevel.CK_OBJECT_HANDLE

generateKeyPair(templatePub, templatePriv, mecha=<PyKCS11.Mechanism object>)[source]

generate a key pair

Parameters:
  • templatePub – template for the public key

  • templatePriv – template for the private key

  • mecha – mechanism to use

Returns:

a tuple of handles (pub, priv)

Return type:

tuple

generateRandom(size=16)[source]

C_GenerateRandom

Parameters:

size (integer) – number of random bytes to get

Note:

the returned value is an instance of ckbytelist. You can easly convert it to a binary string with: bytes(random) or, for Python 2: ''.join(chr(i) for i in random)

getAttributeValue(obj_id, attr, allAsBinary=False)[source]

C_GetAttributeValue

Parameters:
  • obj_id (integer) – object ID returned by findObjects()

  • attr (list) – list of attributes

  • allAsBinary (Boolean) – return all values as binary data; default is False.

Returns:

a list of values corresponding to the list of attributes

Return type:

list

See:

getAttributeValue_fragmented()

Note:

if allAsBinary is True the function do not convert results to Python types (i.e.: CKA_TOKEN to Bool, CKA_CLASS to int, …).

Binary data is returned as ckbytelist type, usable as a list containing only bytes. You can easly convert it to a binary string with: bytes(ckbytelistVariable) or, for Python 2: ''.join(chr(i) for i in ckbytelistVariable)

getAttributeValue_fragmented(obj_id, attr, allAsBinary=False)[source]

Same as getAttributeValue() except that when some attribute is sensitive or unknown an empty value (None) is returned.

Note: this is achived by getting attributes one by one.

See:

getAttributeValue()

getSessionInfo()[source]

C_GetSessionInfo

Returns:

a CK_SESSION_INFO object

initPin(pin)[source]

C_InitPIN

Parameters:

pin – new PIN

isAttributeList(type)[source]

is the type a attribute list value?

Parameters:

type – PKCS#11 type like CKA_WRAP_TEMPLATE

Return type:

bool

isBin(type)[source]

is the type a byte array value?

Parameters:

type – PKCS#11 type like CKA_MODULUS

Return type:

bool

isBool(type)[source]

is the type a boolean value?

Parameters:

type – PKCS#11 type like CKA_ALWAYS_SENSITIVE

Return type:

bool

isNum(type)[source]

is the type a numerical value?

Parameters:

type – PKCS#11 type like CKA_CERTIFICATE_TYPE

Return type:

bool

isString(type)[source]

is the type a string value?

Parameters:

type – PKCS#11 type like CKA_LABEL

Return type:

bool

property lib

Get the low level lib of the owning PyKCS11Lib

login(pin, user_type=1)[source]

C_Login

Parameters:
  • pin (string) – the user’s PIN or None for CKF_PROTECTED_AUTHENTICATION_PATH

  • user_type (integer) – the user type. The default value is CKU_USER. You may also use CKU_SO

logout()[source]

C_Logout

seedRandom(seed)[source]

C_SeedRandom

Parameters:

seed (iterable) – seed material

setAttributeValue(obj_id, template)[source]

C_SetAttributeValue

Parameters:
  • obj_id (integer) – object ID returned by findObjects()

  • template (list) – list of (attribute, value) pairs

Returns:

Nothing

Return type:

None

setPin(old_pin, new_pin)[source]

C_SetPIN

Parameters:
  • old_pin – old PIN

  • new_pin – new PIN

sign(key, data, mecha=<PyKCS11.Mechanism object>)[source]

C_SignInit/C_Sign

Parameters:
  • key (integer) – a key handle, obtained calling findObjects().

  • data ((binary) string or list/tuple of bytes) – the data to be signed

  • mecha (Mechanism) – the signing mechanism to be used (use MechanismRSAPKCS1 for CKM_RSA_PKCS)

Returns:

the computed signature

Return type:

list of bytes

Note:

the returned value is an instance of ckbytelist. You can easly convert it to a binary string with: bytes(ckbytelistSignature) or, for Python 2: ''.join(chr(i) for i in ckbytelistSignature)

unwrapKey(unwrappingKey, wrappedKey, template, mecha=<PyKCS11.Mechanism object>)[source]

C_UnwrapKey

Parameters:
  • unwrappingKey (integer) – the unwrapping key handle

  • wrappedKey ((binary) string or list/tuple of bytes) – the bytes of the wrapped key

  • template – template for the unwrapped key

  • mecha (Mechanism) – the decrypt mechanism to be used (use MechanismRSAPKCS1 for CKM_RSA_PKCS)

Returns:

the unwrapped key object

Return type:

integer

verify(key, data, signature, mecha=<PyKCS11.Mechanism object>)[source]

C_VerifyInit/C_Verify

Parameters:
  • key (integer) – a key handle, obtained calling findObjects().

  • data ((binary) string or list/tuple of bytes) – the data that was signed

  • signature ((binary) string or list/tuple of bytes) – the signature to be verified

  • mecha (Mechanism) – the signing mechanism to be used (use MechanismRSAPKCS1 for CKM_RSA_PKCS)

Returns:

True if signature is valid, False otherwise

Return type:

bool

wrapKey(wrappingKey, key, mecha=<PyKCS11.Mechanism object>)[source]

C_WrapKey

Parameters:
  • wrappingKey (integer) – a wrapping key handle

  • key (integer) – a handle of the key to be wrapped

  • mecha (Mechanism) – the encrypt mechanism to be used (use MechanismRSAPKCS1 for CKM_RSA_PKCS)

Returns:

the wrapped key bytes

Return type:

list of bytes

Note:

the returned value is an instance of ckbytelist. You can easily convert it to a binary string with: bytes(ckbytelistData) or, for Python 2: ''.join(chr(i) for i in ckbytelistData)

class PyKCS11.XOR_BASE_AND_DATA_Mechanism(data)[source]

CKM_XOR_BASE_AND_DATA key derivation mechanism

Parameters:

data – a byte array to xor the key with

class PyKCS11.ckbytelist(data=None)[source]

add a __repr__() method to the LowLevel equivalent