python-pkcs11-0.7.0/0000775000372000037200000000000013717606456015020 5ustar travistravis00000000000000python-pkcs11-0.7.0/docs/0000775000372000037200000000000013717606456015750 5ustar travistravis00000000000000python-pkcs11-0.7.0/docs/api.rst0000664000372000037200000001124113717606207017244 0ustar travistravis00000000000000API Reference ============= .. contents:: Section Contents :depth: 2 :local: Classes ------- .. automodule:: pkcs11 :members: :exclude-members: lib .. class:: lib(so) Initialises the PKCS#11 library. Only one PKCS#11 library can be initialised. :param str so: Path to the PKCS#11 library to initialise. .. method:: get_slots(token_present=False) Returns a list of PKCS#11 device slots known to this library. :param token_present: If true, will limit the results to slots with a token present. :rtype: list(Slot) .. method:: get_tokens(token_label=None, token_serial=None, token_flags=None, slot_flags=None, mechanisms=None) Generator yielding PKCS#11 tokens matching the provided parameters. See also :meth:`get_token`. :param str token_label: Optional token label. :param bytes token_serial: Optional token serial. :param TokenFlag token_flags: Optional bitwise token flags. :param SlotFlag slot_flags: Optional bitwise slot flags. :param iter(Mechanism) mechanisms: Optional required mechanisms. :rtype: iter(Token) .. method:: get_token(token_label=None, token_serial=None, token_flags=None, slot_flags=None, mechanisms=None) Returns a single token or raises either :class:`pkcs11.exceptions.NoSuchToken` or :class:`pkcs11.exceptions.MultipleTokensReturned`. See also :meth:`get_tokens`. :param str token_label: Optional token label. :param bytes token_serial: Optional token serial. :param TokenFlag token_flags: Optional bitwise token flags. :param SlotFlag slot_flags: Optional bitwise slot flags. :param iter(Mechanism) mechanisms: Optional required mechanisms. :rtype: Token .. method:: reinitialize() Reinitializes the loaded PKCS#11 library. :rtype: None .. attribute:: cryptoki_version PKCS#11 Cryptoki standard version (:class:`tuple`). .. attribute:: manufacturer_id Library vendor's name (:class:`str`). .. attribute:: library_description Description of the vendor's library (:class:`str`). .. attribute:: library_version Vendor's library version (:class:`tuple`). .. autoclass:: Slot() :members: :inherited-members: .. autoclass:: Token() :members: :inherited-members: .. autoclass:: Session() :members: :inherited-members: Token Objects ~~~~~~~~~~~~~ The following classes relate to :class:`Object` objects on the :class:`Token`. .. autoclass:: Object() :members: :inherited-members: .. autoclass:: Key(Object) :members: .. autoclass:: SecretKey(Key) :members: .. autoclass:: PublicKey(Key) :members: .. autoclass:: PrivateKey(Key) :members: .. autoclass:: DomainParameters(Object) :members: .. autoclass:: Certificate(Object) :members: Object Capabilities ~~~~~~~~~~~~~~~~~~~ Capability mixins for :class:`Object` objects. .. autoclass:: EncryptMixin() :members: .. autoclass:: DecryptMixin() :members: .. autoclass:: SignMixin() :members: .. autoclass:: VerifyMixin() :members: .. autoclass:: WrapMixin() :members: .. autoclass:: UnwrapMixin() :members: .. autoclass:: DeriveMixin() :members: Constants --------- .. automodule:: pkcs11.constants :members: :inherited-members: :undoc-members: Key Types & Mechanisms ---------------------- .. automodule:: pkcs11.mechanisms :members: :inherited-members: :undoc-members: .. autoclass:: pkcs11.MechanismInfo() :members: :inherited-members: Exceptions ---------- .. automodule:: pkcs11.exceptions :members: :undoc-members: Utilities --------- General Utilities ~~~~~~~~~~~~~~~~~ .. automodule:: pkcs11.util :members: :undoc-members: RSA Key Utilities ~~~~~~~~~~~~~~~~~ .. automodule:: pkcs11.util.rsa :members: :undoc-members: DSA Key Utilities ~~~~~~~~~~~~~~~~~ .. automodule:: pkcs11.util.dsa :members: :undoc-members: DH Key Utilities ~~~~~~~~~~~~~~~~ .. automodule:: pkcs11.util.dh :members: :undoc-members: EC Key Utilities ~~~~~~~~~~~~~~~~ .. automodule:: pkcs11.util.ec :members: :undoc-members: X.509 Certificate Utilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: pkcs11.util.x509 :members: :undoc-members: python-pkcs11-0.7.0/docs/Makefile0000664000372000037200000000114413717606207017402 0ustar travistravis00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python -msphinx SPHINXPROJ = PythonPKCS11 SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)python-pkcs11-0.7.0/docs/conf.py0000664000372000037200000001170413717606207017244 0ustar travistravis00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Python PKCS#11 documentation build configuration file, created by # sphinx-quickstart on Sat May 20 11:47:34 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import sphinx_rtd_theme sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.intersphinx', ] autodoc_member_order = 'bysource' intersphinx_mapping = {'python': ('https://docs.python.org/3', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Python PKCS#11' copyright = '2017, Danielle Madeley' author = 'Danielle Madeley' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '' # The full version, including alpha/beta/rc tags. release = '' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'PythonPKCS11doc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'PythonPKCS11.tex', 'Python PKCS\\#11 Documentation', 'Danielle Madeley', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pythonpkcs11', 'Python PKCS#11 Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'PythonPKCS11', 'Python PKCS#11 Documentation', author, 'PythonPKCS11', 'One line description of project.', 'Miscellaneous'), ] python-pkcs11-0.7.0/docs/opensc.rst0000664000372000037200000001674713717606207020002 0ustar travistravis00000000000000Using with SmartCard-HSM (Nitrokey HSM) ======================================= Support for the SmartCard-HSM and Nitrokey HSM is provided through the `OpenSC `_ project. The device is not a cryptographic accelerator. Only key generation and the private key operations (sign and decrypt) are supported. Public key operations should be done by extracting the public key and working on the computer. The following mechanisms are available: +------------------+-----------------------+-----------------------------------+ | Cipher | Capabilities | Variants | +==================+=======================+===================================+ | RSA (v1.5/X.509) | Decrypt, Verify, Sign | MD5, SHA1, SHA256, SHA384, SHA512 | +------------------+-----------------------+-----------------------------------+ | ECDSA | Sign | SHA1 | +------------------+-----------------------+-----------------------------------+ | ECDH | Derive | Cofactor Derive | +------------------+-----------------------+-----------------------------------+ Session lifetime objects are not supported and the value of :attr:`pkcs11.constants.Attribute.TOKEN` and the `store` keyword argument are ignored. All objects will be stored to the device. The following named curves are supported: * secp192r1 (aka prime192v1) * secp256r1 (aka prime256v1) * brainpoolP192r1 * brainpoolP224r1 * brainpoolP256r1 * brainpoolP320r1 * secp192k1 * secp256k1 (the Bitcoin curve) More information is available `in the Nitrokey FAQ `_. Getting Started --------------- Initialize the device with `sc-hsm-tool`, e.g. :: sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 648219 --label "Nitrokey" See `the documentation `_ for more information on the parameters. The OpenSC PKCS #11 module is `opensc-pkcs11.so`. Generating Keys --------------- RSA ~~~ :: import pkcs11 with token.open(user_pin='1234', rw=True) as session: pub, priv = session.generate_keypair(pkcs11.KeyType.RSA, 2048, store=True, label="My RSA Keypair") EC ~~ :: with token.open(user_pin='1234', rw=True) as session: ecparams = session.create_domain_parameters( pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: pkcs11.util.ec.encode_named_curve_parameters('secp256r1'), }, local=True) pub, priv = ecparams.generate_keypair(store=True, label="My EC Keypair") Exporting Public Keys for External Use -------------------------------------- While we don't want our private keys to leave the boundary of our HSM, we can extract the public keys for use with a cryptographic library of our choosing. :ref:`importing-keys` has more information on functions for exporting keys. RSA ~~~ `PyCrypto` example: :: from pkcs11 import KeyType, ObjectClass, Mechanism from pkcs11.util.rsa import encode_rsa_public_key from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 # Extract public key key = session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) key = RSA.importKey(encode_rsa_public_key(key)) # Encryption on the local machine cipher = PKCS1_v1_5.new(key) crypttext = cipher.encrypt(b'Data to encrypt') # Decryption in the HSM priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) plaintext = priv.decrypt(crypttext, mechanism=Mechanism.RSA_PKCS) ECDSA ~~~~~ `oscrypto` example: :: from pkcs11 import KeyType, ObjectClass, Mechanism from pkcs11.util.ec import encode_ec_public_key, encode_ecdsa_signature from oscrypto.asymmetric import load_public_key, ecdsa_verify # Sign data in the HSM priv = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PRIVATE_KEY) signature = priv.sign(b'Data to sign', mechanism=Mechanism.ECDSA_SHA1) # Encode as ASN.1 for interchange signature = encode_ecdsa_signature(signature) # Extract the public key pub = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PUBLIC_KEY) # Verify the signature on the local machine key = load_public_key(encode_ec_public_key(pub)) ecdsa_verify(key, signature, b'Data to sign', 'sha1') ECDH ~~~~ Smartcard-HSM can generate a shared key via ECDH key exchange. .. warning:: Where possible, e.g. over networks, you should use ephemeral keys, to allow for perfect forward secrecy. Smartcard HSM's ECDH is only useful when need to repeatedly retrieve the same shared secret, e.g. encrypting files in a hybrid cryptosystem. `cryptography` example: :: from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.serialization import \ Encoding, PublicFormat, load_der_public_key # Retrieve our keypair, with our public key encoded for interchange alice_priv = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PRIVATE_KEY) alice_pub = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PUBLIC_KEY) alice_pub = encode_ec_public_key(alice_pub) # Bob generates a keypair, with their public key encoded for # interchange bob_priv = ec.generate_private_key(ec.SECP256R1, default_backend()) bob_pub = bob_priv.public_key().public_bytes( Encoding.DER, PublicFormat.SubjectPublicKeyInfo, ) # Bob converts Alice's key to internal format and generates their # shared key bob_shared_key = bob_priv.exchange( ec.ECDH(), load_der_public_key(alice_pub, default_backend()), ) key = alice_priv.derive_key( KeyType.GENERIC_SECRET, 256, mechanism_param=( KDF.NULL, None, # SmartcardHSM doesn't accept DER-encoded EC_POINTs for derivation decode_ec_public_key(bob_pub, encode_ec_point=False) [Attribute.EC_POINT], ), ) alice_shared_key = key[Attribute.VALUE] When decoding the other user's `EC_POINT` for passing into the key derivation the standard says to pass a raw octet string (set `encode_ec_point` to False), however some PKCS #11 implementations require a DER-encoded octet string (i.e. the format of the :attr:`pkcs11.constants.Attribute.EC_POINT` attribute). Encrypting Files ---------------- The device only supports asymmetric mechanisms. To do file encryption, you will need to generate AES keys locally, which you can encrypt with your RSA public key (this is how the Nitrokey storage key works); or by using ECDH to generate a shared secret from a locally generated public key. Debugging --------- The parameter `OPENSC_DEBUG` will enable debugging of the OpenSC driver. A higher number indicates more verbosity. Thanks ------ Thanks to Nitrokey for their support of open software and sending a Nitrokey HSM to test with `python-pkcs11`. python-pkcs11-0.7.0/docs/concurrency.rst0000664000372000037200000000556413717606207021040 0ustar travistravis00000000000000.. _concurrency: Concurrency =========== PKCS#11 is able to be accessed from multiple threads. The specification recommends setting a flag to enable access from multiple threads, however due to the existence of the `global interpreter lock `_ preventing concurrent execution of Python threads, you will not be preempted inside a single PKCS#11 call and so the flag has not been set to maximise compatibility with PKCS#11 implementations. Most of the calls exposed in our API make a single call into PKCS#11, however, multi-step calls, such as searching for objects, encryption, decryption, etc. can be preempted as control is returned to the interpreter (e.g. by generators). The :class:`pkcs11.Session` class includes a reenterant lock (:class:`threading.RLock`) to control access to these multi-step operations, and prevent threads from interfering with each other. .. warning:: Libraries that monkeypatch Python, such as `gevent`, may be supported, but are not currently being tested. The lock is not released until the iterator is consumed (or garbage collected). However, if you do not consume the iterator, you will never complete the action and further actions will raise :class:`pkcs11.exceptions.OperationActive` (cancelling iterators is not currently supported). Reenterant Sessions ------------------- Thread safety aside, a number of PKCS#11 libraries do not support the same token being logged in from simultaneous sessions (within the same process), and so it can be advantageous to use a single session across multiple threads. Sessions can often live for a very long time, but failing to close a session may leak resources into your memory space, HSM daemon or HSM hardware. A simple reference counting reenterant session object can be used. :: import logging import threading import pkcs11 LOCK = threading.Lock() LIB = pkcs11.lib(settings.PKCS11_MODULE) class Session(object): """Reenterant session wrapper.""" session = None refcount = 0 @classmethod def acquire(cls): with LOCK: if cls.refcount == 0: token = LIB.get_token(token_label=settings.PKCS11_TOKEN) cls.session = token.open(user_pin=settings.PKCS11_TOKEN_PASSPHRASE) cls.refcount += 1 return cls.session @classmethod def release(cls): with LOCK: cls.refcount -= 1 if cls.refcount == 0: cls.session.close() cls.session = None def __enter__(self): return self.acquire() def __exit__(self, type_, value, traceback): self.release() The multi-step locking primitives in the :class:`pkcs11.Session` should allow you to operate safely. python-pkcs11-0.7.0/docs/index.rst0000664000372000037200000000032513717606207017603 0ustar travistravis00000000000000.. include:: ../README.rst Contents ======== .. toctree:: :maxdepth: 2 applied api concurrency opensc Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-pkcs11-0.7.0/docs/applied.rst0000664000372000037200000013006313717606207020115 0ustar travistravis00000000000000Applied PKCS #11 ================ `PKCS `_ #11 is the name given to a standard defining an API for cryptographic hardware. While it was developed by RSA, as part of a suite of standards, the standard is not exclusive to RSA ciphers and is meant to cover a wide range of cryptographic possibilities. PKCS #11 is most closely related to Java's JCE and Microsoft's CAPI. .. contents:: Section Contents :depth: 2 :local: Concepts in PKCS #11 -------------------- Slots and Tokens ~~~~~~~~~~~~~~~~ A `slot` originally referred to a single card slot on a smartcard device that could accept a `token`. A token was a smartcard that contained secure, encrypted keys and certificates. You would insert your smartcard (token) into the slot, and use its contents to do cryptographic operations. Nowadays the distinction is more blurry. Many USB-key HSMs appear as a single slot containing a hardwired single token (their internal storage). Server devices often make use of software tokens (`softcards`), which appear as slots within PKCS #11, but no physical device exists. These devices can also feature physical slots and `accelerator slots`. .. seealso:: Slots have :attr:`pkcs11.Slot.flags` which can tell you something about what kind of slot this is. Tokens are secured with a passphrase (PIN). Not all implementations use pins in their underlying implementation, but these are required for PKCS#11. Some implementations let you control the behaviour of their PKCS #11 module in ways not specified by the specification through environment variables (e.g. default token pins). .. note:: The PKCS #11 library is running within your process, using your memory, etc. It may talk to a daemon to access the underlying hardware, or it may be talking directly. Environment variables set on your process can be used to configure the behaviour of the library, check the documentation for your device. Finding Tokens ^^^^^^^^^^^^^^ Tokens are identified by a label or serial number. You can retrieve all tokens matching search parameters: :: for slot in lib.get_slots(): token = slot.get_token() # Check the parameters if token.label == '...': break :: for token in lib.get_tokens(token_label='smartcard'): print(token) Retrieving a single token has a shortcut function: :: try: lib.get_token(token_label='smartcard') except NoSuchToken: pass except MultipleTokensReturned: pass Mechanisms and Capabilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Different devices support different cryptographic operations. In PKCS #11 mechanisms refer to the combination of cipher (e.g. AES), hash function (e.g. SHA512) and block mode (e.g. CBC). Mechanisms also exist for generating keys, and deriving keys and parameters. The capabilities of a mechanism indicate what types of operations can be carried out with the mechanism, e.g. encryption, signing, key generation. Not all devices support all mechanisms. Some may support non-standard mechanisms. Not all devices support the same capabilities for mechanisms or same key lengths. This information can be retrieved via :meth:`pkcs11.Slot.get_mechanisms` and :meth:`pkcs11.Slot.get_mechanism_info` or from your device documentation. Some mechanisms require `mechanism parameters`. These are used to provide additional context to the mechanism that does not form part of the key. Examples of mechanism parameters are initialisation vectors for block modes, salts, key derivation functions, and other party's shared secrets (for Diffie-Hellman). .. seealso:: The :class:`pkcs11.mechanisms.Mechanism` type includes information on the required parameters for common mechanisms. A complete list of `current mechanisms `_ and `historical mechanisms `_ includes the mechanism parameters and input requirements for each mechanism. Objects and Attributes ~~~~~~~~~~~~~~~~~~~~~~ An object is a piece of cryptographic information stored on a `token`. Objects have a `class` (e.g. private key) which is exposed in `python-pkcs11` as a Python class. They also have a number of other attributes depending on their class. There are three main classes of object: * keys (symmetric secret keys and asymmetric public and private keys); * domain parameters (storing the parameters used to generate keys); and * certificates (e.g. `X.509 `_ certificates). .. note:: Irregardless of the PKCS #11 specification, not all devices reliably handle all object attributes. They can also have different defaults. `python-pkcs11` tries to abstract that as much as possible to enable writing portable code. .. seealso:: :class:`pkcs11.constants.Attribute` describes the available attributes and their Python types. **biginteger** One type is handled specially: `biginteger`, an arbitrarily long integer in network byte order. Although Python can handle arbitrarily long integers, many other systems cannot and pass these types around as byte arrays, and more often than not, that is an easier form to handle them in. `biginteger` attributes can be specified as :class:`bytes`, :class:`bytearray` or an iterable of byte-sized integers. If you do have integers, you can convert them to :class:`bytes` using :func:`pkcs11.util.biginteger`. Finding Objects ^^^^^^^^^^^^^^^ Objects can be found on a `token` using their attributes. Usually an `ID` or `LABEL`. :: for obj in session.get_objects({ Attribute.CLASS: ObjectClass.SECRET_KEY, Attribute.LABEL: 'aes256', }): print(obj) Finding a specific key is so common there's a shortcut function: :: try: key = session.get_key(label='aes256') except NoSuchKey: pass except MultipleObjectsReturned: pass Keys ~~~~ There are three classes of key objects: * symmetric secret keys; * asymmetric public keys; and * asymmetric private keys. The following attributes can be set for keys: .. glossary:: PRIVATE Private objects can only be accessed by logged in sessions. LOCAL This key was generated on the device. EXTRACTABLE The key can be extracted from the HSM. SENSITIVE The key is sensitive and cannot be removed from the device in clear text. ALWAYS_SENSITIVE The key has never not been `SENSITIVE`. NEVER_EXTRACTABLE The key has never been `EXTRACTABLE`. ALWAYS_AUTHENTICATE The key requires authentication every time it's used. .. note:: Keys should be generated on the HSM rather than imported. Generally only public keys should not be `PRIVATE` and `SENSITIVE`. Allowing private keys to be accessed defeats the purpose of securing your keys in a HSM. `python-pkcs11` sets meaningful defaults. Domain Parameters ~~~~~~~~~~~~~~~~~ Domain parameters are the parameters used to generate cryptographic keys (e.g. the name of the elliptic curve being used). They are public information. Obscuring the domain parameters does not increase the security of a cryptosystem. Typically the domain parameters form part of a protocol specification, and RFCs exist giving pre-agreed, named domain parameters for cryptosystems. In `python-pkcs11` domain parameters can either be stored as an object in your HSM, or loaded via some other mechanism (e.g. in your code) and used directly without creating a HSM object. .. seealso:: OpenSSL can be used to generate unique or named domain parameters for `Diffie-Hellman `_, `DSA `_ and `EC `_. :mod:`pkcs11.util` includes modules for creating and decoding domain parameters. Sessions ~~~~~~~~ Accessing a token is done by opening a session. Sessions can be public or logged in. Only a logged in session can access objects marked as `private`. Depending on your device, some functions may also be unavailable. .. warning:: It is important to close sessions when you are finished with them. Some devices will leak resources if sessions aren't closed. Where possible you should use sessions via a context manager. Concepts related to PKCS #11 ---------------------------- Binary Formats and Padding ~~~~~~~~~~~~~~~~~~~~~~~~~~ PKCS #11 is `protocol agnostic` and does not define or implement any codecs for the storing of enciphered data, keys, initialisation vectors, etc. outside the HSM. [#]_ For example, CBC mechanisms will not include the initialization vector. You must choose a storage/transmission format that suits your requirements. Some mechanisms require input data to be `padded` to a certain block size. Standardized `PAD` variants of many mechanisms exist based on upstream specifications. For other mechanisms PKCS #11 does not define any specific algorithms, and you must choose one that suits your requirements. .. seealso:: Lots of standards exist for the storing and transmission of cryptographic data. If you're not implementing a specific protocol, there may still be an RFC standard with a Python implementation to ensure people can understand your binary data in the future. See also: * `RFC 5652 (Cryptographic Message Standard) (supercedes PKCS #7) `_ .. [#] It does define types for data `inside` the HSM, e.g. attribute data types and binary formats (e.g. EC parameters, X.509 certificates). PKCS #15 ~~~~~~~~ PKCS #15 defines a standard for storing cryptographic objects within the HSM device to enable interoperability between devices and tokens. PKCS #15 is often referenced in conjunction with PKCS #11 as the storage format used on the `tokens`. ASN.1, DER, BER ~~~~~~~~~~~~~~~ ASN.1 is a data model for storing structured information. DER and BER are binary representations of that data model which are used extensively in cryptography, e.g. for storing RSA key objects, X.509 certificates and elliptic curve information. Accessing ASN.1 encoded objects is mostly left to packages other than `python-pkcs11`, however :mod:`pkcs11.util` does include some utilities to encode and decode objects where required for working with PKCS #11 itself (e.g. converting PKCS #1 encoded RSA keys into PKCS #11 objects and generating parameters for elliptic curves). PEM ~~~ `PEM `_ is a standard for handling cryptographic objects. It is a base64 encoded version of the binary DER object. The label indicates the type of object, and thus what ASN.1 model to use. `python-pkcs11` does not include PEM parsing, you should include another package if required. :mod:`asn1crypto.pem` is a dependency of `python-pkcs11`. Getting a Session ----------------- Given a PKCS #11 library (`.so`) that is stored in the environment as `PKCS11_MODULE`. To open a read-only session on a token named `smartcard`: :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='smartcard') with token.open() as session: print(session) To open a user session with the passphrase/pin `secret`: :: with token.open(user_pin='secret') as session: print(session) To open a read/write session: :: with token.open(rw=True, user_pin='secret') as session: print(session) .. seealso:: :meth:`pkcs11.Token.open` has more options for opening the session. Generating Keys --------------- Keys can either live for the lifetime of the `session` or be stored on the token. Storing keys requires a read only session. To store keys pass `store=True`. When storing keys it is recommended to set a `label` or `id`, so you can find the key again. Symmetric Keys ~~~~~~~~~~~~~~ AES ^^^ AES keys can be generated by specifying the key length: :: from pkcs11 import KeyType key = session.generate_key(KeyType.AES, 256) Generally AES keys are considered secret. However if you're using your HSM to generate keys for use with local AES (e.g. in hybrid encryption systems). You can do the following: :: from pkcs11 import KeyType, Attribute key = session.generate_key(KeyType.AES, 256, template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) # This is the secret key print(key[Attribute.VALUE]) .. glossary:: VALUE Secret key (as `biginteger`). DES2/3 ^^^^^^ .. warning:: DES2 and DES3 are considered insecure because their short key lengths are brute forcable with modern hardware. DES2/3 keys are fixed length. :: from pkcs11 import KeyType des2 = session.generate_key(KeyType.DES2) des3 = session.generate_key(KeyType.DES3) These secret key objects have the same parameters as for AES. Asymmetric Keypairs ~~~~~~~~~~~~~~~~~~~ RSA ^^^ RSA keypairs can be generated by specifying the length of the modulus: :: from pkcs11 import KeyType public, private = session.generate_keypair(KeyType.RSA, 2048) The default public exponent is `65537`. You can specify an alternative: :: from pkcs11 import KeyType, Attribute public, private = session.generate_keypair(KeyType.RSA, 2048, public_template={Attribute.PUBLIC_EXPONENT: ...}) # This is the public key print(public[Attribute.MODULUS]) print(public[Attribute.PUBLIC_EXPONENT]) The public key has two parameters: .. glossary:: MODULUS Key modulus (as `biginteger`). PUBLIC_EXPONENT Public exponent (as `biginteger`). These can be exported as RFC 2437 (PKCS #1) DER-encoded binary using :func:`pkcs11.util.rsa.encode_rsa_public_key`. DSA ^^^ DSA keypairs can be generated by specifying the length of the prime in bits. :: from pkcs11 import KeyType public, private = session.generate_keypair(KeyType.RSA, 2048) This will generate unique domain parameters for a key. If you want to create a key for given domain parameters, see `DSA from Domain Parameters`_. The public key has a single important attribute: .. glossary:: VALUE Public key (as biginteger). This can be encoded in RFC 3279 format with :func:`pkcs11.util.dsa.encode_dsa_public_key`. From Domain Parameters ~~~~~~~~~~~~~~~~~~~~~~ .. note:: Choosing domain parameters is not covered in this document. Domain parameters are often either specified by the requirements you are implementing for, or have a standard implementation to derive quality parameters. Some domain parameters (e.g. choice of elliptic curve) can drastically weaken the cryptosystem. .. _`DSA from Domain Parameters`: DSA ^^^ Diffie-Hellman key pairs require three domain parameters, specified as `bigintegers`. .. glossary:: BASE The prime base (g) (as `biginteger`). PRIME The prime modulus (p) (as `biginteger`). SUBPRIME The subprime (q) (as `biginteger`). :: from pkcs11 import Attribute parameters = session.create_domain_parameters(KeyType.DSA, { Attribute.PRIME: b'prime...', Attribute.BASE: b'base...', Attribute.SUBPRIME: b'subprime...', }, local=True) public, private = parameters.generate_keypair() `RFC 3279 `_ defines a standard ASN.1 encoding for DSA parameters, which can be loaded with :func:`pkcs11.util.dsa.decode_dsa_domain_parameters`: :: params = session.create_domain_parameters( KeyType.DSA, decode_dsa_domain_parameters(b'DER-encoded parameters'), local=True) If supported, unique domain parameters can also be generated for a given `PRIME` length (e.g. 1024 bits) with :meth:`pkcs11.Session.generate_domain_parameters`: :: params = session.generate_domain_parameters(KeyType.DSA, 1024) These can be encoded into the standard ASN.1 DER encoding using :func:`pkcs11.util.dsa.encode_dsa_domain_parameters`. .. note:: You can create a DSA key directly from freshly generated domain parameters with :meth:`Session.generate_keypair`. Diffie-Hellman ^^^^^^^^^^^^^^ Diffie-Hellman key pairs require several domain parameters, specified as `bigintegers`. There are two forms of Diffie-Hellman domain parameters: PKCS #3 and X9.42. .. glossary:: BASE The prime base (g) (as `biginteger`). PRIME The prime modulus (p) (as `biginteger`). SUBPRIME (X9.42 only) The subprime (q) (as `biginteger`). :: from pkcs11 import Attribute parameters = session.create_domain_parameters(KeyType.DH, { Attribute.PRIME: b'prime...', Attribute.BASE: b'base...', }, local=True) public, private = parameters.generate_keypair() `RFC 3279 `_ defines a standard ASN.1 encoding for DH parameters, which can be loaded with :func:`pkcs11.util.dh.decode_x9_42_dh_domain_parameters`: :: params = session.create_domain_parameters( KeyType.X9_42_DH, decode_x9_42_dh_domain_parameters(b'DER-encoded parameters'), local=True) If supported, unique domain parameters can also be generated for a given `PRIME` length (e.g. 512 bits) with :meth:`pkcs11.Session.generate_domain_parameters`: :: params = session.generate_domain_parameters(KeyType.DH, 512) X9.42 format domain parameters can be encoded back to their RFC 3279 format with :func:`pkcs11.util.dh.encode_x9_42_dh_domain_parameters`. Key pairs can be generated from the domain parameters: :: public, private = parameters.generate_keypair() # This is the public key print(public[Attribute.VALUE]) The public key has a single important attribute: .. glossary:: VALUE Public key (as biginteger). This can be encoded in RFC 3279 format with :func:`pkcs11.util.dh.encode_dh_public_key`. Elliptic Curve ^^^^^^^^^^^^^^ Elliptic curves require a domain parameter describing the curve. Curves can be described in two ways: * As named curves; or * As a complete set of parameters. Not all devices support both specifications. You can determine what curve parameters your device supports by checking :meth:`pkcs11.Slot.get_mechanism_info` :class:`pkcs11.constants.MechanismFlag`. Both specifications are specified using the same `attribute`: .. glossary:: EC_PARAMS Curve parameters (as DER-encoded X9.62 bytes). :: from pkcs11 import Attribute parameters = session.create_domain_parameters(KeyType.EC, Attribute.EC_PARAMS: b'DER-encoded X9.62 parameters ...', }, local=True) public, private = parameters.generate_keypair() Named curves (e.g. `secp256r1`) can be specified like this: :: from pkcs11 import Attribute from pkcs11.util.ec import encode_named_curve_parameters parameters = session.create_domain_parameters(KeyType.EC, { Attribute.EC_PARAMS: encode_named_curve_parameters('secp256r1') }, local=True) Key pairs can be generated from the domain parameters: :: public, private = parameters.generate_keypair() # This is the public key print(public[Attribute.EC_POINT]) The public key as a single important attribute: .. glossary:: EC_POINT Public key (as X9.62 DER-encoded bytes). .. _importing-keys: Importing/Exporting Keys ------------------------ .. warning:: It is best to only import/export public keys. You should, whenever possible, generate and store secret and private keys within the boundary of your HSM. The following utility methods will convert keys encoded in their canonical DER-encoded into attributes that can be used with :meth:`pkcs11.Session.create_object`. .. note:: PEM certificates are base64-encoded versions of the canonical DER-encoded forms used in `python-pkcs11`. Conversion between PEM and DER can be achieved using `asn1crypto.pem `_. AES/DES ~~~~~~~ .. warning:: Whenever possible, generate and store secret keys within the boundary of your HSM. AES and DES keys are stored as binary bytes in :attr:`pkcs11.constants.Attribute.VALUE`. Keys must be marked as `EXTRACTABLE` and not `SENSITIVE` to export. RSA ~~~ To import a PKCS #1 DER-encoded RSA key, the following utility methods are provided: * :func:`pkcs11.util.rsa.decode_rsa_public_key`, and * :func:`pkcs11.util.rsa.decode_rsa_private_key`. To export an RSA public key in PKCS #1 DER-encoded format, use :func:`pkcs11.util.rsa.encode_rsa_public_key`. DSA ~~~ To import an RFC 3279 DER-encoded DSA key, the following utility methods are provided: * :func:`pkcs11.util.dsa.decode_dsa_domain_parameters`, and * :func:`pkcs11.util.dsa.decode_dsa_public_key`. To export a DSA public key, use: * :func:`pkcs11.util.dsa.encode_dsa_domain_parameters`, and * :func:`pkcs11.util.dsa.encode_dsa_public_key`. Elliptic Curve ~~~~~~~~~~~~~~ The :attr:`pkcs11.constants.Attribute.EC_PARAMS` and :attr:`pkcs11.constants.Attribute.EC_POINT` attributes for elliptic curves are already in DER-encoded X9.62 format. You can import keys from OpenSSL using: * :func:`pkcs11.util.ec.decode_ec_public_key`, and * :func:`pkcs11.util.ec.decode_ec_private_key`. To export an EC public key in OpenSSL format, use :func:`pkcs11.util.ec.encode_ec_public_key`. X.509 ~~~~~ The function :func:`pkcs11.util.x509.decode_x509_public_key` is provided to extract public keys from X.509 DER-encoded certificates, which is capable of handling RSA, DSA and ECDSA keys. Encryption/Decryption --------------------- Ciphers can generally be considered in two categories: * Symmetric ciphers (e.g. AES), which use a single key to encrypt and decrypt, and are good at encrypting large amounts of data; and * Asymmetric ciphers (e.g. RSA), which use separate public and private keys, and are good for securing small amounts of data. Symmetric ciphers operate on blocks of data, and thus are used along with a `block mode `_. `python-pkcs11` can consume block mode ciphers via a generator. Asymmetric ciphers are used for public-key cryptography. They cannot encrypt large amounts of data. Typically these ciphers are used to encrypt a symmetric session key, which does the bulk of the work, in a so-called hybrid cryptosystem. +----------+-------------+---------------------+------------------+ | Cipher | Block modes | Block Size (IV len) | Mechanism Param | +==========+=============+=====================+==================+ | AES | Yes | 128 bits | IV (except EBC) | +----------+-------------+---------------------+------------------+ | DES2/3 | Yes | 64 bits | IV (except EBC) | +----------+-------------+---------------------+------------------+ | RSA | No | N/A | Optional | +----------+-------------+---------------------+------------------+ AES ~~~ The `AES `_ cipher requires you to specify a block mode as part of the `mechanism`. The default block mode is `CBC with PKCS padding `_, which can handle data not padded to the block size and requires you to supply an initialisation vector of 128-bits of good random. A number of other mechanisms are available: +-------------+-----+----------------+---------------------------------+ | Mechanism | IV | Input Size | Notes | +=============+=====+================+=================================+ | AES_ECB | No | 128-bit blocks | Only suitable for key-wrapping. | | | | | Identical blocks encrypt | | | | | identically! | +-------------+-----+----------------+---------------------------------+ | AES_CBC | Yes | 128-bit blocks | | +-------------+-----+----------------+---------------------------------+ | AES_CBC_PAD | Yes | Any | Default mechanism | +-------------+-----+----------------+---------------------------------+ | AES_OFB | Yes | Any | | +-------------+-----+----------------+---------------------------------+ | AES_CFB_* | Yes | Any | 3 modes: AES_CFB8, AES_CFB64, | | | | | and AES_CFB128. | +-------------+-----+----------------+---------------------------------+ | AES_CTS | Yes | >= 128-bit | | +-------------+-----+----------------+---------------------------------+ | AES_CTR | Not currently supported [#]_ | +-------------+ | | AES_GCM | | +-------------+ | | AES_CGM | | +-------------+--------------------------------------------------------+ .. [#] AES encryption with multiple mechanism parameters not currently implemented due to lack of hardware supporting these mechanisms. .. warning:: **Initialisation vectors** An initialization vector (IV) or starting variable (SV) is data that is used by several modes to randomize the encryption and hence to produce distinct ciphertexts even if the same plaintext is encrypted multiple times. An initialization vector has different security requirements than a key, so the IV usually does not need to be secret. However, in most cases, it is important that an initialization vector is never reused under the same key. For CBC and CFB, reusing an IV leaks some information about the first block of plaintext, and about any common prefix shared by the two messages. For OFB and CTR, reusing an IV completely destroys security. In CBC mode, the IV must, in addition, be unpredictable at encryption time; in particular, the (previously) common practice of re-using the last ciphertext block of a message as the IV for the next message is insecure. We recommend using :meth:`pkcs11.Session.generate_random` to create a quality IV. A simple example: :: # Given an AES key `key` iv = session.generate_random(128) ciphertext = key.encrypt(plaintext, mechanism_param=iv) plaintext = key.decrypt(ciphertext, mechanism_param=iv) Or using an alternative mechanism: :: from pkcs11 import Mechanism iv = session.generate_random(128) ciphertext = key.encrypt(plaintext, mechanism=Mechanism.AES_OFB, mechanism_param=iv) Large amounts of data can be passed as a generator: :: buffer_size = 8192 with \\ open(file_in, 'rb') as input, \\ open(file_out, 'wb') as output: # A generator yielding chunks of the file chunks = iter(lambda: input.read(buffer_size), '') for chunk in key.encrypt(chunks, mechanism_param=iv, buffer_size=buffer_size): output.write(chunk) .. note:: These mechanisms do not store the IV. You must store the IV yourself, e.g. on the front of the ciphertext. It is safe to store an IV in the clear. DES2/3 ~~~~~~ .. warning:: DES2 and DES3 are considered insecure because their short key lengths are brute forcable with modern hardware. DES2/3 have the same block mode options as AES. The block size is 64 bits, which is the size of the initialization vector. :: # Given an DES3 key `key` iv = session.generate_random(64) ciphertext = key.encrypt(plaintext, mechanism_param=iv) plaintext = key.decrypt(ciphertext, mechanism_param=iv) RSA ~~~ The default RSA cipher is `PKCS #1 OAEP `_ A number of other mechanisms are available: +-----------------------+------------+-------------------------+-----------------------+ | Mechanism | Parameters | Input Length | Notes | +=======================+============+=========================+=======================+ | RSA_PKCS | None | <= key length - 11 | RSA v1.5. Don't use | | | | | for new applications. | +-----------------------+------------+-------------------------+-----------------------+ | RSA_PKCS_OAEP | See below | <= k - 2 - 2hLen | Default mechanism. | +-----------------------+------------+-------------------------+-----------------------+ | RSA_X_509 | None | key length | Raw mode. No padding. | +-----------------------+------------+-------------------------+-----------------------+ | RSA_PKCS_TPM_1_1 | None | <= key length - 11 - 5 | See TCPA TPM | | | | | Specification Version | | | | | 1.1b | +-----------------------+------------+-------------------------+-----------------------+ | RSA_PKCS_OAEP_TPM_1_1 | See below | <= k - 2 - 2hLen | | +-----------------------+------------+-------------------------+-----------------------+ A simple example using the default parameters: :: # Given an RSA key pair `public, private` ciphertext = public.encrypt(plaintext) plaintext = private.decrypt(ciphertext) RSA OAEP can optionally take a tuple of `(hash algorithm, mask generating function and source data)` as the mechanism parameter: :: ciphertext = public.encrypt(plaintext, mechanism=Mechanism.RSA_PKCS_OAEP, mechanism_param=(Mechanism.SHA_1, MGF.SHA1, None)) Signing/Verifying ----------------- Signing and verification mechanisms require two components: * the cipher; and * the hashing function. Raw versions for some mechanisms also exist. These require you to do your own hashing outside of PKCS #11. Signing functions typically work on a finite length of data, so the signing of large amounts of data requires hashing with a secure one-way hash function. AES ~~~ A `MAC` is required for signing with AES. The default mechanism is `AES_MAC`. :: # Given a secret key, `key` signature = key.sign(data) assert key.verify(data, signature) DES2/3 ~~~~~~ A `MAC` is required for signing with DES. The default mechanism is `SHA512_HMAC` (aka HMAC-SHA512). Operation is the same as for `AES`. RSA ~~~ The default signing and verification mechanism for RSA is `RSA_SHA512_PKCS`. Other mechanisms are available: +-------------------+-------------------------------------------+ | Mechanism | Notes | +===================+===========================================+ | RSA_PKCS | No hashing. Supply your own. | +-------------------+-------------------------------------------+ | SHA*_RSA_PKCS | SHAx message digesting. | +-------------------+-------------------------------------------+ | RSA_PKCS_PSS | Optionally takes a tuple of parameters. | +-------------------+ | | SHA*_RSA_PKCS_PSS | | +-------------------+-------------------------------------------+ | RSA_9796 | ISO/IES 9796 RSA signing. | | | Use `PSS` instead. | +-------------------+-------------------------------------------+ | RSA_X_509 | X.509 (raw) RSA signing. | | | You must supply your own padding. | +-------------------+-------------------------------------------+ | RSA_X9_31 | X9.31 RSA signing. | +-------------------+-------------------------------------------+ Simple example using the default mechanism: :: # Given a private key `private` signature = private.sign(data) # Given a public key `public` assert public.verify(data, signature) RSA PSS optionally takes a tuple of `(hash algorithm, mask generating function and salt length)` as the mechanism parameter: :: signature = private.sign(data, mechanism=Mechanism.RSA_PKCS_PSS, mechanism_param=(Mechanism.SHA_1, MGF.SHA1, 20)) DSA ~~~ The default signing and verification mechanism for RSA is `DSA_SHA512`. Other mechanisms are available: +------------+-------------------------------------------+ | Mechanism | Notes | +============+===========================================+ | DSA | No hashing. 20, 28, 32, 48 or 64 bits. | +------------+-------------------------------------------+ | DSA_SHA* | DSA with SHAx message digesting. | +------------+-------------------------------------------+ :: # Given a private key `private` signature = private.sign(data) # Given a public key `public` assert public.verify(data, signature) The parameters `r` and `s` are concatenated together as a single byte string (each value is 20 bytes long for a total of 40 bytes). To convert to the ASN.1 encoding (e.g. as used by X.509) use :func:`pkcs11.util.dsa.encode_dsa_signature`. To convert from the ASN.1 encoding into PKCS #11 encoding use :func:`pkcs11.util.ec.decode_dsa_signature`. ECDSA ~~~~~ The default signing and verification mechanism for ECDSA is `ECDSA_SHA512`. Other mechanisms are available: +------------+-------------------------------------------+ | Mechanism | Notes | +============+===========================================+ | ECDSA | No hashing. Input truncated to 1024 bits. | +------------+-------------------------------------------+ | ECDSA_SHA* | ECDSA with SHAx message digesting. | +------------+-------------------------------------------+ :: # Given a private key `private` signature = private.sign(data) # Given a public key `public` assert public.verify(data, signature) The parameters `r` and `s` are concatenated together as a single byte string (both values are the same length). To convert to the ASN.1 encoding (e.g. as used by X.509) use :func:`pkcs11.util.ec.encode_ecdsa_signature`. To convert from the ASN.1 encoding into PKCS #11 encoding use :func:`pkcs11.util.ec.decode_ecdsa_signature`. Wrapping/Unwrapping ------------------- The expectation when using HSMs is that secret and private keys never leave the secure boundary of the HSM. However, there is a use case for transmitting secret and private keys over insecure mediums. We can do this using key wrapping. Key wrapping is similar to encryption and decryption except instead of turning plaintext into crypttext it turns key objects into crypttext and vice versa. Keys must be marked as `EXTRACTABLE` to remove them from the HSM, even wrapped. Key wrapping mechanisms usually mirror encryption mechanisms. AES ~~~ Default key wrapping mode is `AES_ECB`. ECB is considered safe for key wrapping due to the lack of repeating blocks. Other mechanisms, such as the new `AES_KEY_WRAP` (if available), are also possible.. The key we're wrapping can be any sensitive key, either a secret key or a private key. In this example we're extracting an AES secret key: :: # Given two secret keys, `key1` and `key2`, we can extract an encrypted # version of `key2` crypttext = key1.wrap_key(key2) Wrapping doesn't store any parameters about the keys. We must supply those to import the key. :: key = key1.unwrap_key(ObjectClass.SECRET_KEY, KeyType.AES, crypttext) DES2/3 ~~~~~~ Default key wrapping mode is `DES3_ECB`. ECB is considered safe for key wrapping due to the lack of repeating blocks. Other mechanisms are available. Operation is the same as for `AES`. RSA ~~~ The key we're wrapping can be any sensitive key, either a secret key or a private key. In this example we're extracting an AES secret key: :: # Given a public key, `public`, and a secret key `key`, we can extract an encrypted version of `key` crypttext = public.wrap_key(key) Wrapping doesn't store any parameters about the keys. We must supply those to import the key. :: # Given a private key, `private`, matching `public` above we can decrypt # and import `key`. key = private.unwrap_key(ObjectClass.SECRET_KEY, KeyType.AES, crypttext) Deriving Shared Keys -------------------- .. warning:: Key derivation mechanisms do not verify the authenticity of the other party. Your application should include a mechanism to verify the other user's public key is really from that user to avoid man-in-the-middle attacks. Where possible use an existing protocol. Diffie-Hellman ~~~~~~~~~~~~~~ DH lets us derive a shared key using shared domain parameters, our private key and the other party's public key, which is passed as a mechanism parameter. The default DH derivation mechanism is `DH_PKCS_DERIVE`, which uses the algorithm described in PKCS #3. .. note:: Other DH derivation mechanisms including X9.42 derivation are not currently supported. :: # Given our DH private key `private` and the other party's public key # `other_public` key = private.derive_key( KeyType.AES, 128, mechanism_param=other_public) If the other user's public key was encoded using RFC 3279, we can decode this with :func:`pkcs11.util.dh.decode_dh_public_key`: :: from pkcs11.util.dh import decode_dh_public_key key = private.derive_key( KeyType.AES, 128, mechanism_param=decode_dh_public_key(encoded_public_key)) And we can encode our public key for them using :func:`pkcs11.util.dh.encode_dh_public_key`: :: from pkcs11.util.dh import encode_dh_public_key # Given our DH public key `public` encoded_public_key = encode_dh_public_key(public) The shared derived key can now be used for any appropriate mechanism. If you want to extract the shared key from the HSM, you can mark the key as `EXTRACTABLE`: :: key = private.derive_key( KeyType.AES, 128, mechanism_param=other_public, template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) # This is our shared secret key print(key[Attribute.VALUE]) EC Diffie-Hellman ~~~~~~~~~~~~~~~~~ ECDH is supported using the `ECDH1_DERIVE` mechanism, similar to plain DH, except that the mechanism parameter is a tuple consisting of 3 parameters: * a key derivation function (KDF); * a shared value; and * the other user's public key. The supported KDFs vary from device to device, check your HSM documentation. For :attr:`pkcs11.mechanisms.KDF.NULL` (the most widely supported KDF), the shared value must be `None`. .. note:: Other ECDH derivation mechanisms including co-factor derivation and MQV derivation are not currently supported. :: from pkcs11 import KeyType, KDF # Given our DH private key `private` and the other party's public key # `other_public` key = private.derive_key( KeyType.AES, 128, mechanism_param=(KDF.NULL, None, other_public)) The value of the other user's public key should usually be a raw byte string however some implementations require a DER-encoded byte string (i.e. the same format as `EC_POINT`) [#]_. Use the `encode_ec_point` parameter to :func:`pkcs11.util.ec.decode_ec_public_key`. +-----------------+----------------------------------+ | Implementation | Other user's `EC_POINT` encoding | +=================+==================================+ | SoftHSM v2 | DER-encoded | +-----------------+----------------------------------+ | Nitrokey HSM | Raw | +-----------------+----------------------------------+ | Thales nCipher | ? | +-----------------+----------------------------------+ If you want to extract the shared key from the HSM, you can mark the key as `EXTRACTABLE`: :: key = private.derive_key( KeyType.AES, 128, mechanism_param=(KDF.NULL, None, other_public), template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) # This is our shared secret key print(key[Attribute.VALUE]) .. [#] The incompatibility comes from this being unspecified in earlier versions of PKCS #11, although why they made it a different format to `EC_POINT` is unclear. Digesting and Hashing --------------------- PKCS #11 exposes the ability to hash or digest data via a number of mechanisms. For performance reasons, this is rarely done in the HSM, and is usually done in your process. The only advantage of using this function over :mod:`hashlib` is the ability to digest :class:`pkcs11.Key` objects. To digest a message (e.g. with SHA-256): :: from pkcs11 import Mechanism digest = session.digest(data, mechanism=Mechanism.SHA_256) You can also pass an iterable of data: :: with open(file_in, 'rb') as input: # A generator yielding chunks of the file chunks = iter(lambda: input.read(buffer_size), '') digest = session.digest(chunks, mechanism=Mechanism.SHA_512) Or a key (if supported): :: digest = session.digest(public_key, mechanism=Mechanism.SHA_1) Or even a combination of keys and data: :: digest = session.digest((b'HEADER', key), mechanism=Mechanism.SHA_1) Certificates ------------ Certificates can be stored in the HSM as objects. PKCS#11 is limited in its handling of certificates, and does not provide features like parsing of X.509 etc. These should be handled in an external library (e.g. `asn1crypto`. PKCS#11 will not set attributes on the certificate based on the `VALUE` and these must be specified when creating the object. X.509 ~~~~~ The following attributes are defined: .. glossary:: VALUE The complete X.509 certificate (BER-encoded) SUBJECT The certificate subject (DER-encoded X.509 distinguished name) ISSUER The certificate issuer (DER-encoded X.509 distinguished name) SERIAL The certificate serial (DER-encoded integer) Additionally an extended set of attributes can be stored if your HSM supports it: .. glossary:: START_DATE The certificate start date (notBefore) END_DATE The certificate end date (notAfter) HASH_OF_SUBJECT_PUBLIC_KEY The identifier of the subject's public key (bytes) HASH_OF_ISSUER_PUBLIC_KEY The identifier of the issuer's public key (bytes) Importing Certificates ^^^^^^^^^^^^^^^^^^^^^^ :func:`pkcs11.util.x509.decode_x509_certificate` can be used to decode X.509 certificates for storage in the HSM: :: from pkcs11.util.x509 import decode_x509_certificate cert = self.session.create_object(decode_x509_certificate(b'DER encoded X.509 cert...')) Exporting Certificates ^^^^^^^^^^^^^^^^^^^^^^ The full certificate is stored as `VALUE`. Any X.509 capable library can use this data, e.g. `asn1crypto` or `PyOpenSSL`. OpenSSL: :: import OpenSSL from pkcs11 import Attribute, ObjectClass for cert in session.get_objects({ Attribute.CLASS: ObjectClass.CERTIFICATE, }): # Convert from DER-encoded value to OpenSSL object cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_ASN1, cert[Attribute.VALUE], ) # Retrieve values from the certificate subject = cert.get_subject() # Convert to PEM format cert = OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, cert ) asn1crypto: :: from asn1crypto import pem, x509 der_bytes = cert[Attribute.VALUE] # Load a certificate object from the DER-encoded value cert = x509.Certificate.load(der_bytes) # Write out a PEM encoded value pem_bytes = pem.armor('CERTIFICATE', der_bytes) python-pkcs11-0.7.0/docs/make.bat0000664000372000037200000000145213717606207017351 0ustar travistravis00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=python -msphinx ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=PythonPKCS11 if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The Sphinx module was not found. Make sure you have Sphinx installed, echo.then set the SPHINXBUILD environment variable to point to the full echo.path of the 'sphinx-build' executable. Alternatively you may add the echo.Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd python-pkcs11-0.7.0/requirements.txt0000664000372000037200000000032413717606207020275 0ustar travistravis00000000000000# # This file is autogenerated by pip-compile # To update, run: # # pip-compile --output-file requirements.txt requirements.in # aenum==2.0.7 ; python_version < "3.6" asn1crypto==0.22.0 cached-property==1.3.0 python-pkcs11-0.7.0/PKG-INFO0000664000372000037200000004514613717606456016127 0ustar travistravis00000000000000Metadata-Version: 1.1 Name: python-pkcs11 Version: 0.7.0 Summary: PKCS#11 (Cryptoki) support for Python Home-page: https://github.com/danni/python-pkcs11 Author: Danielle Madeley Author-email: danielle@madeley.id.au License: UNKNOWN Description: Python PKCS#11 - High Level Wrapper API ======================================= A high level, "more Pythonic" interface to the PKCS#11 (Cryptoki) standard to support HSM and Smartcard devices in Python. The interface is designed to follow the logical structure of a HSM, with useful defaults for obscurely documented parameters. Many APIs will optionally accept iterables and act as generators, allowing you to stream large data blocks for symmetric encryption. python-pkcs11 also includes numerous utility functions to convert between PKCS #11 data structures and common interchange formats including PKCS #1 and X.509. python-pkcs11 is fully documented and has a full integration test suite for all features, with continuous integration against multiple HSM platforms including: * Thales nCipher * Opencryptoki TPM * OpenSC/Smartcard-HSM/Nitrokey HSM Source: https://github.com/danni/python-pkcs11 Documentation: http://python-pkcs11.readthedocs.io/en/latest/ Getting Started --------------- Install from Pip: :: pip install python-pkcs11 Or build from source: :: python setup.py build Assuming your PKCS#11 library is set as `PKCS11_MODULE` and contains a token named `DEMO`: AES ~~~ :: import pkcs11 # Initialise our PKCS#11 library lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an AES key in this session key = session.generate_key(pkcs11.KeyType.AES, 256) # Get an initialisation vector iv = session.generate_random(128) # AES blocks are fixed at 128 bits # Encrypt our data crypttext = key.encrypt(data, mechanism_param=iv) 3DES ~~~~ :: import pkcs11 # Initialise our PKCS#11 library lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate a DES key in this session key = session.generate_key(pkcs11.KeyType.DES3) # Get an initialisation vector iv = session.generate_random(64) # DES blocks are fixed at 64 bits # Encrypt our data crypttext = key.encrypt(data, mechanism_param=iv) RSA ~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an RSA keypair in this session pub, priv = session.generate_keypair(pkcs11.KeyType.RSA, 2048) # Encrypt as one block crypttext = pub.encrypt(data) DSA ~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an DSA keypair in this session pub, priv = session.generate_keypair(pkcs11.KeyType.DSA, 1024) # Sign signature = priv.sign(data) ECDSA ~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an EC keypair in this session from a named curve ecparams = session.create_domain_parameters( pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: pkcs11.util.ec.encode_named_curve_parameters('prime256v1'), }, local=True) pub, priv = ecparams.generate_keypair() # Sign signature = priv.sign(data) Diffie-Hellman ~~~~~~~~~~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') with token.open() as session: # Given shared Diffie-Hellman parameters parameters = session.create_domain_parameters(pkcs11.KeyType.DH, { pkcs11.Attribute.PRIME: prime, # Diffie-Hellman parameters pkcs11.Attribute.BASE: base, }) # Generate a DH key pair from the public parameters public, private = parameters.generate_keypair() # Share the public half of it with our other party. _network_.write(public[Attribute.VALUE]) # And get their shared value other_value = _network_.read() # Derive a shared session key with perfect forward secrecy session_key = private.derive_key( pkcs11.KeyType.AES, 128, mechanism_param=other_value) Elliptic-Curve Diffie-Hellman ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') with token.open() as session: # Given DER encocded EC parameters, e.g. from # openssl ecparam -outform der -name parameters = session.create_domain_parameters(pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: ecparams, }) # Generate a DH key pair from the public parameters public, private = parameters.generate_keypair() # Share the public half of it with our other party. _network_.write(public[pkcs11.Attribute.EC_POINT]) # And get their shared value other_value = _network_.read() # Derive a shared session key session_key = private.derive_key( pkcs11.KeyType.AES, 128, mechanism_param=(pkcs11.KDF.NULL, None, other_value)) Tested Compatibility -------------------- +------------------------------+--------------+-----------------+--------------+-------------------+ | Functionality | SoftHSMv2 | Thales nCipher | Opencryptoki | OpenSC (Nitrokey) | +==============================+==============+=================+==============+===================+ | Get Slots/Tokens | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Get Mechanisms | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Initialize token | Not implemented | +------------------------------+-------------------------------------------------------------------+ | Slot events | Not implemented | +------------------------------+-------------------------------------------------------------------+ | Alternative authentication | Not implemented | | path | | +------------------------------+-------------------------------------------------------------------+ | `Always authenticate` keys | Not implemented | +-------------+----------------+--------------+-----------------+--------------+-------------------+ | Create/Copy | Keys | Works | Works | Errors | Create | | +----------------+--------------+-----------------+--------------+-------------------+ | | Certificates | Caveats [1]_ | Caveats [1]_ | Caveats [1]_ | ? | | +----------------+--------------+-----------------+--------------+-------------------+ | | Domain Params | Caveats [1]_ | Caveats [1]_ | ? | N/A | +-------------+----------------+--------------+-----------------+--------------+-------------------+ | Destroy Object | Works | N/A | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Generate Random | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Seed Random | Works | N/A | N/A | N/A | +------------------------------+--------------+-----------------+--------------+-------------------+ | Digest (Data & Keys) | Works | Caveats [2]_ | Works | Works | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | AES | Generate key | Works | Works | Works | N/A | | +---------------------+--------------+-----------------+--------------+ | | | Encrypt/Decrypt | Works | Works | Works | | | +---------------------+--------------+-----------------+--------------+ | | | Wrap/Unwrap | ? [3]_ | Works | Errors | | | +---------------------+--------------+-----------------+--------------+ | | | Sign/Verify | Works | Works [4]_ | N/A | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DES2/ | Generate key | Works | Works | Works | N/A | | DES3 +---------------------+--------------+-----------------+--------------+ | | | Encrypt/Decrypt | Works | Works | Works | | | +---------------------+--------------+-----------------+--------------+ | | | Wrap/Unwrap | ? | ? | ? | | | +---------------------+--------------+-----------------+--------------+ | | | Sign/Verify | ? | ? | ? | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | RSA | Generate key pair | Works | Works | Works | Works [4]_ [8]_ | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Encrypt/Decrypt | Works | Works | Works | Decrypt only [9]_ | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Wrap/Unwrap | Works | Works | Works | N/A | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Sign/Verify | Works | Works | Works | Works | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DSA | Generate parameters | Works | Error | N/A | N/A | | +---------------------+--------------+-----------------+ | | | | Generate key pair | Works | Caveats [5]_ | | | | +---------------------+--------------+-----------------+ | | | | Sign/Verify | Works | Works [4]_ | | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DH | Generate parameters | Works | N/A | N/A | N/A | | +---------------------+--------------+-----------------+ | | | | Generate key pair | Works | Caveats [6]_ | | | | +---------------------+--------------+-----------------+ | | | | Derive Key | Works | Caveats [7]_ | | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | EC | Generate key pair | Caveats [6]_ | ? [3]_ | N/A | Works | | +---------------------+--------------+-----------------+ +-------------------+ | | Sign/Verify (ECDSA) | Works [4]_ | ? [3]_ | | Sign only [9]_ | | +---------------------+--------------+-----------------+ +-------------------+ | | Derive key (ECDH) | Works | ? [3]_ | | ? | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | Proprietary extensions | N/A | Not implemented | N/A | N/A | +------------------------------+--------------+-----------------+--------------+-------------------+ .. [1] Device supports limited set of attributes. .. [2] Digesting keys is not supported. .. [3] Untested: requires support in device. .. [4] Default mechanism not supported, must specify a mechanism. .. [5] From existing domain parameters. .. [6] Local domain parameters only. .. [7] Generates security warnings about the derived key. .. [8] `store` parameter is ignored, all keys are stored. .. [9] Encryption/verify not supported, extract the public key Python version: * 3.4 (with `aenum`) * 3.5 (with `aenum`) * 3.6 PKCS#11 versions: * 2.11 * 2.20 * 2.40 Feel free to send pull requests for any functionality that's not exposed. The code is designed to be readable and expose the PKCS #11 spec in a straight-forward way. If you want your device supported, get in touch! More info on PKCS #11 --------------------- The latest version of the PKCS #11 spec is available from OASIS: http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html You should also consult the documentation for your PKCS #11 implementation. Many implementations expose additional vendor options configurable in your environment, including alternative features, modes and debugging information. License ------- MIT License Copyright (c) 2017 Danielle Madeley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Platform: UNKNOWN Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Security :: Cryptography python-pkcs11-0.7.0/pkcs11/0000775000372000037200000000000013717606456016122 5ustar travistravis00000000000000python-pkcs11-0.7.0/pkcs11/_utils.pyx0000664000372000037200000000203013717606207020150 0ustar travistravis00000000000000""" Type wrangling utility functions. """ from .constants import * from .mechanisms import * cdef CK_BYTE_buffer(length): """Make a buffer for `length` CK_BYTEs.""" return array(shape=(length,), itemsize=sizeof(CK_BYTE), format='B') cdef CK_ULONG_buffer(length): """Make a buffer for `length` CK_ULONGs.""" return array(shape=(length,), itemsize=sizeof(CK_ULONG), format='L') cdef bytes _pack_attribute(key, value): """Pack a Attribute value into a bytes array.""" try: pack, _ = ATTRIBUTE_TYPES[key] return pack(value) except KeyError: raise NotImplementedError("Can't pack this %s. " "Expand ATTRIBUTE_TYPES!" % key) cdef _unpack_attributes(key, value): """Unpack a Attribute bytes array into a Python value.""" try: _, unpack = ATTRIBUTE_TYPES[key] return unpack(bytes(value)) except KeyError: raise NotImplementedError("Can't unpack this %s. " "Expand ATTRIBUTE_TYPES!" % key) python-pkcs11-0.7.0/pkcs11/defaults.py0000664000372000037200000001324613717606207020303 0ustar travistravis00000000000000""" Default mappings for various key types and mechanisms. None of this is provided for in PKCS#11 and its correctness should not be assumed. """ from datetime import datetime from struct import Struct from .constants import ( Attribute, CertificateType, MechanismFlag, ObjectClass, ) from .mechanisms import Mechanism, KeyType, MGF DEFAULT_GENERATE_MECHANISMS = { KeyType.AES: Mechanism.AES_KEY_GEN, KeyType.DES2: Mechanism.DES2_KEY_GEN, KeyType.DES3: Mechanism.DES3_KEY_GEN, KeyType.DH: Mechanism.DH_PKCS_KEY_PAIR_GEN, KeyType.DSA: Mechanism.DSA_KEY_PAIR_GEN, KeyType.EC: Mechanism.EC_KEY_PAIR_GEN, KeyType.RSA: Mechanism.RSA_PKCS_KEY_PAIR_GEN, KeyType.X9_42_DH: Mechanism.X9_42_DH_KEY_PAIR_GEN, KeyType.EC_EDWARDS: Mechanism.EC_EDWARDS_KEY_PAIR_GEN, } """ Default mechanisms for generating keys. """ _ENCRYPTION = MechanismFlag.ENCRYPT | MechanismFlag.DECRYPT _SIGNING = MechanismFlag.SIGN | MechanismFlag.VERIFY _WRAPPING = MechanismFlag.WRAP | MechanismFlag.UNWRAP DEFAULT_KEY_CAPABILITIES = { KeyType.AES: _ENCRYPTION | _SIGNING | _WRAPPING, KeyType.DES2: _ENCRYPTION | _SIGNING | _WRAPPING, KeyType.DES3: _ENCRYPTION | _SIGNING | _WRAPPING, KeyType.DH: MechanismFlag.DERIVE, KeyType.DSA: _SIGNING, KeyType.EC: _SIGNING | MechanismFlag.DERIVE, KeyType.RSA: _ENCRYPTION | _SIGNING | _WRAPPING, KeyType.GENERIC_SECRET: 0, KeyType.EC_EDWARDS: _SIGNING, } """ Default capabilities for generating keys. """ DEFAULT_ENCRYPT_MECHANISMS = { KeyType.AES: Mechanism.AES_CBC_PAD, KeyType.DES2: Mechanism.DES3_CBC_PAD, KeyType.DES3: Mechanism.DES3_CBC_PAD, KeyType.RSA: Mechanism.RSA_PKCS_OAEP, } """ Default mechanisms for encrypt/decrypt. """ DEFAULT_SIGN_MECHANISMS = { KeyType.AES: Mechanism.AES_MAC, KeyType.DES2: Mechanism.DES3_MAC, KeyType.DES3: Mechanism.DES3_MAC, KeyType.DSA: Mechanism.DSA_SHA512, KeyType.EC: Mechanism.ECDSA_SHA512, KeyType.RSA: Mechanism.SHA512_RSA_PKCS, KeyType.EC_EDWARDS: Mechanism.EDDSA, } """ Default mechanisms for sign/verify. """ DEFAULT_WRAP_MECHANISMS = { KeyType.AES: Mechanism.AES_KEY_WRAP, KeyType.DES2: Mechanism.DES3_ECB, KeyType.DES3: Mechanism.DES3_ECB, KeyType.RSA: Mechanism.RSA_PKCS_OAEP, } """ Default mechanism for wrap/unwrap. """ DEFAULT_DERIVE_MECHANISMS = { KeyType.DH: Mechanism.DH_PKCS_DERIVE, KeyType.EC: Mechanism.ECDH1_DERIVE, KeyType.X9_42_DH: Mechanism.X9_42_DH_DERIVE, } """ Default mechanisms for key derivation """ DEFAULT_PARAM_GENERATE_MECHANISMS = { KeyType.DH: Mechanism.DH_PKCS_PARAMETER_GEN, KeyType.DSA: Mechanism.DSA_PARAMETER_GEN, KeyType.X9_42_DH: Mechanism.X9_42_DH_PARAMETER_GEN, } """ Default mechanisms for domain parameter generation """ DEFAULT_MECHANISM_PARAMS = { Mechanism.RSA_PKCS_OAEP: (Mechanism.SHA_1, MGF.SHA1, None), Mechanism.RSA_PKCS_PSS: (Mechanism.SHA_1, MGF.SHA1, 20), } """ Default mechanism parameters """ # (Pack Function, Unpack Function) functions _bool = (Struct('?').pack, lambda v: Struct('?').unpack(v)[0]) _ulong = (Struct('L').pack, lambda v: Struct('L').unpack(v)[0]) _str = (lambda s: s.encode('utf-8'), lambda b: b.decode('utf-8')) _date = (lambda s: s.strftime('%Y%m%d').encode('ascii'), lambda s: datetime.strptime(s.decode('ascii'), '%Y%m%d').date()) _bytes = (bytes, bytes) # The PKCS#11 biginteger type is an array of bytes in network byte order. # If you have an int type, wrap it in biginteger() _biginteger = _bytes def _enum(type_): """Factory to pack/unpack intos into IntEnums.""" pack, unpack = _ulong return (lambda v: pack(int(v)), lambda v: type_(unpack(v))) ATTRIBUTE_TYPES = { Attribute.ALWAYS_AUTHENTICATE: _bool, Attribute.ALWAYS_SENSITIVE: _bool, Attribute.APPLICATION: _str, Attribute.BASE: _biginteger, Attribute.CERTIFICATE_TYPE: _enum(CertificateType), Attribute.CHECK_VALUE: _bytes, Attribute.CLASS: _enum(ObjectClass), Attribute.COEFFICIENT: _biginteger, Attribute.DECRYPT: _bool, Attribute.DERIVE: _bool, Attribute.EC_PARAMS: _bytes, Attribute.EC_POINT: _bytes, Attribute.ENCRYPT: _bool, Attribute.END_DATE: _date, Attribute.EXPONENT_1: _biginteger, Attribute.EXPONENT_2: _biginteger, Attribute.EXTRACTABLE: _bool, Attribute.HASH_OF_ISSUER_PUBLIC_KEY: _bytes, Attribute.HASH_OF_SUBJECT_PUBLIC_KEY: _bytes, Attribute.ID: _bytes, Attribute.ISSUER: _bytes, Attribute.KEY_GEN_MECHANISM: _enum(Mechanism), Attribute.KEY_TYPE: _enum(KeyType), Attribute.LABEL: _str, Attribute.LOCAL: _bool, Attribute.MODIFIABLE: _bool, Attribute.COPYABLE: _bool, Attribute.MODULUS: _biginteger, Attribute.MODULUS_BITS: _ulong, Attribute.NEVER_EXTRACTABLE: _bool, Attribute.OBJECT_ID: _bytes, Attribute.PRIME: _biginteger, Attribute.PRIME_BITS: _ulong, Attribute.PRIME_1: _biginteger, Attribute.PRIME_2: _biginteger, Attribute.PRIVATE: _bool, Attribute.PRIVATE_EXPONENT: _biginteger, Attribute.PUBLIC_EXPONENT: _biginteger, Attribute.SENSITIVE: _bool, Attribute.SERIAL_NUMBER: _bytes, Attribute.SIGN: _bool, Attribute.SIGN_RECOVER: _bool, Attribute.START_DATE: _date, Attribute.SUBJECT: _bytes, Attribute.SUBPRIME: _biginteger, Attribute.SUBPRIME_BITS: _ulong, Attribute.TOKEN: _bool, Attribute.TRUSTED: _bool, Attribute.UNWRAP: _bool, Attribute.URL: _str, Attribute.VALUE: _biginteger, Attribute.VALUE_BITS: _ulong, Attribute.VALUE_LEN: _ulong, Attribute.VERIFY: _bool, Attribute.VERIFY_RECOVER: _bool, Attribute.WRAP: _bool, Attribute.WRAP_WITH_TRUSTED: _bool, } """ Map of attributes to (serialize, deserialize) functions. """ python-pkcs11-0.7.0/pkcs11/_pkcs11_defn.pxd0000664000372000037200000004601613717606207021075 0ustar travistravis00000000000000""" Definitions imported from PKCS11 C headers. """ cdef extern from '../extern/cryptoki.h': ctypedef unsigned char CK_BYTE ctypedef CK_BYTE CK_BBOOL ctypedef CK_BYTE CK_UTF8CHAR ctypedef unsigned char CK_CHAR ctypedef unsigned long int CK_ULONG ctypedef CK_ULONG CK_ATTRIBUTE_TYPE ctypedef CK_ULONG CK_EC_KDF_TYPE ctypedef CK_ULONG CK_FLAGS ctypedef CK_ULONG CK_MECHANISM_TYPE ctypedef CK_ULONG CK_OBJECT_HANDLE ctypedef CK_ULONG CK_RSA_PKCS_MGF_TYPE ctypedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE ctypedef CK_ULONG CK_SESSION_HANDLE ctypedef CK_ULONG CK_SLOT_ID ctypedef CK_ULONG CK_STATE ctypedef enum CK_RV: CKR_OK, CKR_CANCEL, CKR_HOST_MEMORY, CKR_SLOT_ID_INVALID, CKR_GENERAL_ERROR, CKR_FUNCTION_FAILED, CKR_ARGUMENTS_BAD, CKR_NO_EVENT, CKR_NEED_TO_CREATE_THREADS, CKR_CANT_LOCK, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_SENSITIVE, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_NOT_PARALLEL, CKR_FUNCTION_NOT_SUPPORTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_KEY_NOT_NEEDED, CKR_KEY_CHANGED, CKR_KEY_NEEDED, CKR_KEY_INDIGESTIBLE, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_NOT_WRAPPABLE, CKR_KEY_UNEXTRACTABLE, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OBJECT_HANDLE_INVALID, CKR_OPERATION_ACTIVE, CKR_OPERATION_NOT_INITIALIZED, CKR_PIN_INCORRECT, CKR_PIN_INVALID, CKR_PIN_LEN_RANGE, CKR_PIN_EXPIRED, CKR_PIN_LOCKED, CKR_SESSION_CLOSED, CKR_SESSION_COUNT, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_PARALLEL_NOT_SUPPORTED, CKR_SESSION_READ_ONLY, CKR_SESSION_EXISTS, CKR_SESSION_READ_ONLY_EXISTS, CKR_SESSION_READ_WRITE_SO_EXISTS, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_TOKEN_WRITE_PROTECTED, CKR_UNWRAPPING_KEY_HANDLE_INVALID, CKR_UNWRAPPING_KEY_SIZE_RANGE, CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT, CKR_USER_ALREADY_LOGGED_IN, CKR_USER_NOT_LOGGED_IN, CKR_USER_PIN_NOT_INITIALIZED, CKR_USER_TYPE_INVALID, CKR_USER_ANOTHER_ALREADY_LOGGED_IN, CKR_USER_TOO_MANY_TYPES, CKR_WRAPPED_KEY_INVALID, CKR_WRAPPED_KEY_LEN_RANGE, CKR_WRAPPING_KEY_HANDLE_INVALID, CKR_WRAPPING_KEY_SIZE_RANGE, CKR_WRAPPING_KEY_TYPE_INCONSISTENT, CKR_RANDOM_SEED_NOT_SUPPORTED, CKR_RANDOM_NO_RNG, CKR_DOMAIN_PARAMS_INVALID, CKR_BUFFER_TOO_SMALL, CKR_SAVED_STATE_INVALID, CKR_INFORMATION_SENSITIVE, CKR_STATE_UNSAVEABLE, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CRYPTOKI_ALREADY_INITIALIZED, CKR_MUTEX_BAD, CKR_MUTEX_NOT_LOCKED, CKR_NEW_PIN_MODE, CKR_NEXT_OTP, CKR_EXCEEDED_MAX_ITERATIONS, CKR_FIPS_SELF_TEST_FAILED, CKR_LIBRARY_LOAD_FAILED, CKR_PIN_TOO_WEAK, CKR_PUBLIC_KEY_INVALID, CKR_FUNCTION_REJECTED, CKR_VENDOR_DEFINED, ctypedef enum CK_USER_TYPE: CKU_SO, CKU_USER, CKU_CONTEXT_SPECIFIC, cdef enum: CK_TRUE, CK_FALSE, cdef enum: # CK_FLAGS CKF_RW_SESSION, CKF_SERIAL_SESSION, cdef enum: # CKZ CKZ_DATA_SPECIFIED, cdef enum: # CK_STATE CKS_RO_PUBLIC_SESSION, CKS_RO_USER_FUNCTIONS, CKS_RW_PUBLIC_SESSION, CKS_RW_USER_FUNCTIONS, CKS_RW_SO_FUNCTIONS ctypedef struct CK_VERSION: CK_BYTE major CK_BYTE minor ctypedef struct CK_INFO: CK_VERSION cryptokiVersion; CK_UTF8CHAR manufacturerID[32] CK_FLAGS flags CK_UTF8CHAR libraryDescription[32] CK_VERSION libraryVersion; ctypedef struct CK_SLOT_INFO: CK_UTF8CHAR slotDescription[64] CK_UTF8CHAR manufacturerID[32] CK_FLAGS flags CK_VERSION hardwareVersion CK_VERSION firmwareVersion ctypedef struct CK_MECHANISM_INFO: CK_ULONG ulMinKeySize CK_ULONG ulMaxKeySize CK_FLAGS flags ctypedef struct CK_TOKEN_INFO: CK_UTF8CHAR label[32] CK_UTF8CHAR manufacturerID[32] CK_UTF8CHAR model[16] CK_CHAR serialNumber[16] CK_FLAGS flags CK_ULONG ulMaxSessionCount CK_ULONG ulSessionCount CK_ULONG ulMaxRwSessionCount CK_ULONG ulRwSessionCount CK_ULONG ulMaxPinLen CK_ULONG ulMinPinLen CK_ULONG ulTotalPublicMemory CK_ULONG ulFreePublicMemory CK_ULONG ulTotalPrivateMemory CK_ULONG ulFreePrivateMemory CK_VERSION hardwareVersion CK_VERSION firmwareVersion CK_CHAR utcTime[16] ctypedef struct CK_SESSION_INFO: CK_SLOT_ID slotID CK_STATE state CK_FLAGS flags CK_ULONG ulDeviceError ctypedef struct CK_MECHANISM: CK_MECHANISM_TYPE mechanism void *pParameter CK_ULONG ulParameterLen ctypedef struct CK_ATTRIBUTE: CK_ATTRIBUTE_TYPE type void *pValue CK_ULONG ulValueLen ctypedef struct CK_RSA_PKCS_OAEP_PARAMS: CK_MECHANISM_TYPE hashAlg CK_RSA_PKCS_MGF_TYPE mgf CK_RSA_PKCS_OAEP_SOURCE_TYPE source void *pSourceData CK_ULONG ulSourceDataLen ctypedef struct CK_RSA_PKCS_PSS_PARAMS: CK_MECHANISM_TYPE hashAlg CK_RSA_PKCS_MGF_TYPE mgf CK_ULONG sLen ctypedef struct CK_ECDH1_DERIVE_PARAMS: CK_EC_KDF_TYPE kdf CK_ULONG ulSharedDataLen CK_BYTE *pSharedData CK_ULONG ulPublicDataLen CK_BYTE *pPublicData cdef struct CK_FUNCTION_LIST: CK_VERSION version ## pointers to library functions are stored here ## caution: order matters! ## general purpose CK_RV C_Initialize(void *) nogil CK_RV C_Finalize(void *) nogil CK_RV C_GetInfo(CK_INFO *info) nogil CK_RV C_GetFunctionList(CK_FUNCTION_LIST **) nogil ## slot and token management CK_RV C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID *slotList, CK_ULONG *count) nogil CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO *info) nogil CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO *info) nogil CK_RV C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE *mechanismList, CK_ULONG *count) nogil CK_RV C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE mechanism, CK_MECHANISM_INFO *info) nogil CK_RV C_InitToken(CK_SLOT_ID slotID, CK_UTF8CHAR *pPin, CK_ULONG ulPinLen, CK_UTF8CHAR *pLabel) nogil CK_RV C_InitPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR *pPin, CK_ULONG ulPinLen) nogil CK_RV C_SetPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR *pOldPin, CK_ULONG ulOldLen, CK_UTF8CHAR *pNewPin, CK_ULONG ulNewLen) nogil ## session management CK_RV C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, void *application, void *notify, CK_SESSION_HANDLE *handle) nogil CK_RV C_CloseSession(CK_SESSION_HANDLE session) nogil CK_RV C_CloseAllSessions(CK_SLOT_ID slotID) nogil CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO *pInfo) nogil CK_RV C_GetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE *pOperationState, CK_ULONG *pulOperationStateLen) nogil CK_RV C_SetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE *pOperationState, CK_ULONG ulOperationStateLen, CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) nogil CK_RV C_Login(CK_SESSION_HANDLE session, CK_USER_TYPE userType, CK_UTF8CHAR *pin, CK_ULONG pinLen) nogil CK_RV C_Logout(CK_SESSION_HANDLE session) nogil ## object management CK_RV C_CreateObject(CK_SESSION_HANDLE session, CK_ATTRIBUTE *template, CK_ULONG count, CK_OBJECT_HANDLE *key) nogil CK_RV C_CopyObject(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key, CK_ATTRIBUTE *template, CK_ULONG count, CK_OBJECT_HANDLE *new_key) nogil CK_RV C_DestroyObject(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key) nogil CK_RV C_GetObjectSize(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG *pulSize) nogil CK_RV C_GetAttributeValue(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key, CK_ATTRIBUTE *template, CK_ULONG count) nogil CK_RV C_SetAttributeValue(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key, CK_ATTRIBUTE *template, CK_ULONG count) nogil CK_RV C_FindObjectsInit(CK_SESSION_HANDLE session, CK_ATTRIBUTE *template, CK_ULONG count) nogil CK_RV C_FindObjects(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE *objects, CK_ULONG objectsMax, CK_ULONG *objectsLength) nogil CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE session) nogil ## encryption and decryption CK_RV C_EncryptInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) nogil CK_RV C_Encrypt(CK_SESSION_HANDLE session, CK_BYTE *plaintext, CK_ULONG plaintext_len, CK_BYTE *ciphertext, CK_ULONG *ciphertext_len) nogil CK_RV C_EncryptUpdate(CK_SESSION_HANDLE session, CK_BYTE *part_in, CK_ULONG part_in_len, CK_BYTE *part_out, CK_ULONG *part_out_len) nogil CK_RV C_EncryptFinal(CK_SESSION_HANDLE session, CK_BYTE *part_out, CK_ULONG *part_out_len) nogil CK_RV C_DecryptInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) nogil CK_RV C_Decrypt(CK_SESSION_HANDLE session, CK_BYTE *ciphertext, CK_ULONG ciphertext_len, CK_BYTE *plaintext, CK_ULONG *plaintext_len) nogil CK_RV C_DecryptUpdate(CK_SESSION_HANDLE session, CK_BYTE *part_in, CK_ULONG part_in_len, CK_BYTE *part_out, CK_ULONG *part_out_len) nogil CK_RV C_DecryptFinal(CK_SESSION_HANDLE session, CK_BYTE *part_out, CK_ULONG *part_out_len) nogil ## Message digests CK_RV C_DigestInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism) nogil CK_RV C_Digest(CK_SESSION_HANDLE session, CK_BYTE *data, CK_ULONG data_len, CK_BYTE *digest, CK_ULONG *digest_len) nogil CK_RV C_DigestUpdate(CK_SESSION_HANDLE session, CK_BYTE *data, CK_ULONG data_len) nogil CK_RV C_DigestKey(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key) nogil CK_RV C_DigestFinal(CK_SESSION_HANDLE session, CK_BYTE *digest, CK_ULONG *digest_len) nogil ## Signing and MACing CK_RV C_SignInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) nogil CK_RV C_Sign(CK_SESSION_HANDLE session, CK_BYTE *text, CK_ULONG text_len, CK_BYTE *signature, CK_ULONG *sig_len) nogil CK_RV C_SignUpdate(CK_SESSION_HANDLE session, CK_BYTE *part, CK_ULONG part_len) nogil CK_RV C_SignFinal(CK_SESSION_HANDLE session, CK_BYTE *signature, CK_ULONG *sig_len) nogil CK_RV C_SignRecoverInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) nogil CK_RV C_SignRecover(CK_SESSION_HANDLE session, CK_BYTE *text, CK_ULONG text_len, CK_BYTE *signature, CK_ULONG *sig_len) nogil ## Verifying signatures and MACs CK_RV C_VerifyInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) nogil CK_RV C_Verify(CK_SESSION_HANDLE session, CK_BYTE *text, CK_ULONG text_len, CK_BYTE *signature, CK_ULONG sig_len) nogil CK_RV C_VerifyUpdate(CK_SESSION_HANDLE session, CK_BYTE *text, CK_ULONG text_len) nogil CK_RV C_VerifyFinal(CK_SESSION_HANDLE session, CK_BYTE *signature, CK_ULONG sig_len) nogil CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) nogil CK_RV C_VerifyRecover(CK_SESSION_HANDLE session, CK_BYTE *text, CK_ULONG text_len, CK_BYTE *signature, CK_ULONG sig_len) nogil ## dual-function crypto operations CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE session, CK_BYTE *data, CK_ULONG data_len, CK_BYTE *encrypted, CK_ULONG *encrypted_len) nogil CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE session, CK_BYTE *encrypted, CK_ULONG encrypted_len, CK_BYTE *data, CK_ULONG *data_len) nogil CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE session, CK_BYTE *part, CK_ULONG part_len) nogil CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE session, CK_BYTE *text, CK_ULONG text_len) nogil ## key management CK_RV C_GenerateKey(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_ATTRIBUTE *template, CK_ULONG count, CK_OBJECT_HANDLE *key) nogil CK_RV C_GenerateKeyPair(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_ATTRIBUTE *public_template, CK_ULONG public_count, CK_ATTRIBUTE *private_template, CK_ULONG private_count, CK_OBJECT_HANDLE *public_key, CK_OBJECT_HANDLE *private_key) nogil CK_RV C_WrapKey(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE wrapping_key, CK_OBJECT_HANDLE key_to_wrap, CK_BYTE *wrapped_key, CK_ULONG *wrapped_key_len) nogil CK_RV C_UnwrapKey(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE unwrapping_key, CK_BYTE *wrapped_key, CK_ULONG wrapped_key_len, CK_ATTRIBUTE *attrs, CK_ULONG attr_len, CK_OBJECT_HANDLE *unwrapped_key) nogil CK_RV C_DeriveKey(CK_SESSION_HANDLE session, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE src_key, CK_ATTRIBUTE *template, CK_ULONG count, CK_OBJECT_HANDLE *new_key) nogil ## random number generation CK_RV C_SeedRandom(CK_SESSION_HANDLE session, CK_BYTE *seed, CK_ULONG length) nogil CK_RV C_GenerateRandom(CK_SESSION_HANDLE session, CK_BYTE *random, CK_ULONG length) nogil ## parallel processing CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE session) nogil CK_RV C_CancelFunction(CK_SESSION_HANDLE session) nogil ## smart card events CK_RV C_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID *slot, void *pRserved) nogil # The only external API call that must be defined in a PKCS#11 library # All other APIs are taken from the CK_FUNCTION_LIST table ctypedef CK_RV (*C_GetFunctionList_ptr) (CK_FUNCTION_LIST **) nogil python-pkcs11-0.7.0/pkcs11/mechanisms.py0000664000372000037200000005056213717606207020625 0ustar travistravis00000000000000from enum import IntEnum class KeyType(IntEnum): """ Key types known by PKCS#11. Making use of a given key type requires the appropriate :class:`Mechanism` to be available. Key types beginning with an underscore are historic and are best avoided. """ RSA = 0x00000000 """ See the `RSA section `_ of the PKCS #11 specification for valid :class:`Mechanism` and :class:`pkcs11.constants.Attribute` types. """ DSA = 0x00000001 """ See the `DSA section `_ of the PKCS #11 specification for valid :class:`Mechanism` and :class:`pkcs11.constants.Attribute` types. """ DH = 0x00000002 """ PKCS #3 Diffie-Hellman key. See the `Diffie-Hellman section `_ of the PKCS #11 specification for valid :class:`Mechanism` and :class:`pkcs11.constants.Attribute` types. """ EC = 0x00000003 """ See the `Elliptic Curve section `_ of the PKCS #11 specification for valid :class:`Mechanism` and :class:`pkcs11.constants.Attribute` types. """ X9_42_DH = 0x00000004 """ X9.42 Diffie-Hellman key. """ _KEA = 0x00000005 GENERIC_SECRET = 0x00000010 _RC2 = 0x00000011 _RC4 = 0x00000012 _DES = 0x00000013 DES2 = 0x00000014 """ .. warning:: Considered insecure. Use AES where possible. """ DES3 = 0x00000015 """ .. warning:: Considered insecure. Use AES where possible. """ _CAST = 0x00000016 _CAST3 = 0x00000017 _CAST5 = 0x00000018 _CAST128 = 0x00000018 _RC5 = 0x00000019 _IDEA = 0x0000001A _SKIPJACK = 0x0000001B _BATON = 0x0000001C _JUNIPER = 0x0000001D _CDMF = 0x0000001E AES = 0x0000001F """ See the `AES section `_ of PKCS#11 for valid :class:`Mechanism` and :class:`pkcs11.constants.Attribute` types. """ BLOWFISH = 0x00000020 TWOFISH = 0x00000021 SECURID = 0x00000022 HOTP = 0x00000023 ACTI = 0x00000024 CAMELLIA = 0x00000025 ARIA = 0x00000026 _MD5_HMAC = 0x00000027 SHA_1_HMAC = 0x00000028 """ .. warning:: SHA-1 is no longer considered secure. """ _RIPEMD128_HMAC = 0x00000029 _RIPEMD160_HMAC = 0x0000002A SHA256_HMAC = 0x0000002B SHA384_HMAC = 0x0000002C SHA512_HMAC = 0x0000002D SHA224_HMAC = 0x0000002E SEED = 0x0000002F GOSTR3410 = 0x00000030 GOSTR3411 = 0x00000031 GOST28147 = 0x00000032 # from version 3.0 EC_EDWARDS = 0x00000040 _VENDOR_DEFINED = 0x80000000 def __repr__(self): return '' % self.name class Mechanism(IntEnum): """ Cryptographic mechanisms known by PKCS#11. The list of supported cryptographic mechanisms for a :class:`pkcs11.Slot` can be retrieved with :meth:`pkcs11.Slot.get_mechanisms()`. Mechanisms beginning with an underscore are historic and best avoided. Descriptions of the `current `_ and `historical `_ mechanisms, including their valid :class:`pkcs11.constants.Attribute` types and `mechanism_param` can be found in the PKCS#11 specification. Additionally, while still in the `current` spec, a number of mechanisms including cryptographic hash functions and certain block modes are no longer considered secure, and should not be used for new applications, e.g. MD2, MD5, SHA1, ECB. """ RSA_PKCS_KEY_PAIR_GEN = 0x00000000 """ RSA PKCS #1 v1.5 key generation. .. note:: Default for generating :attr:`KeyType.RSA` keys. """ RSA_PKCS = 0x00000001 """ RSA PKCS #1 v1.5 general purpose mechanism. .. warning:: Consider using the more robust PKCS#1 OAEP. """ RSA_PKCS_TPM_1_1 = 0x00004001 """ .. warning:: Consider using the more robust PKCS#1 OAEP. """ RSA_PKCS_OAEP = 0x00000009 """ RSA PKCS #1 OAEP (v2.0+) .. note:: Default for encrypting/decrypting with :attr:`KeyType.RSA` keys. Optionally takes a `mechanism_param` which is a tuple of: * message digest algorithm used to calculate the digest of the encoding parameter (:class:`Mechanism`), default is :attr:`Mechanism.SHA_1`; * mask generation function to use on the encoded block (:class:`MGF`), default is :attr:`MGF.SHA1`; * data used as the input for the encoding parameter source (:class:`bytes`), default is None. """ RSA_PKCS_OAEP_TPM_1_1 = 0x00004002 RSA_X_509 = 0x00000003 """ X.509 (raw) RSA. No padding, supply your own. """ RSA_9796 = 0x00000002 """ ISO/IEC 9796 RSA. .. warning:: DS1 and DS3 are considered broken. The PKCS #11 spec doesn't specify which scheme is used. Use `PSS` instead. """ MD2_RSA_PKCS = 0x00000004 """ .. warning:: Not considered secure. """ MD5_RSA_PKCS = 0x00000005 """ .. warning:: Not considered secure. """ SHA1_RSA_PKCS = 0x00000006 """ .. warning:: SHA-1 is no longer considered secure. """ SHA224_RSA_PKCS = 0x00000046 SHA256_RSA_PKCS = 0x00000040 SHA384_RSA_PKCS = 0x00000041 SHA512_RSA_PKCS = 0x00000042 """ .. note:: Default for signing/verification with :attr:`KeyType.RSA` keys. """ RSA_PKCS_PSS = 0x0000000D """ RSA PSS without hashing. PSS schemes optionally take a tuple of: * message digest algorithm used to calculate the digest of the encoding parameter (:class:`Mechanism`), default is :attr:`Mechanism.SHA_1`; * mask generation function to use on the encoded block (:class:`MGF`), default is :attr:`MGF.SHA1`; and * salt length, default is 20 """ SHA1_RSA_PKCS_PSS = 0x0000000E """ .. warning:: SHA-1 is no longer considered secure. """ SHA224_RSA_PKCS_PSS = 0x00000047 SHA256_RSA_PKCS_PSS = 0x00000043 SHA384_RSA_PKCS_PSS = 0x00000044 SHA512_RSA_PKCS_PSS = 0x00000045 RSA_X9_31_KEY_PAIR_GEN = 0x0000000A RSA_X9_31 = 0x0000000B SHA1_RSA_X9_31 = 0x0000000C """ .. warning:: SHA-1 is no longer considered secure. """ _RIPEMD128_RSA_PKCS = 0x00000007 _RIPEMD160_RSA_PKCS = 0x00000008 DSA_KEY_PAIR_GEN = 0x00000010 """ .. note:: Default mechanism for generating :attr:`KeyType.DSA` keypairs Requires :class:`pkcs11.DomainParameters`. """ DSA = 0x00000011 """ DSA without hashing. """ DSA_SHA1 = 0x00000012 """ .. warning:: SHA-1 is no longer considered secure. """ DSA_SHA224 = 0x00000013 DSA_SHA256 = 0x00000014 DSA_SHA384 = 0x00000015 DSA_SHA512 = 0x00000016 """ DSA with SHA512 hashing. .. note:: Default for signing/verification with :attr:`KeyType.DSA` keys. """ DH_PKCS_KEY_PAIR_GEN = 0x00000020 """ .. note:: Default mechanism for generating :attr:`KeyType.DH` key pairs. This is the mechanism defined in PKCS #3. Requires :class:`pkcs11.DomainParameters` of :attr:`pkcs11.constants.Attribute.BASE` and :attr:`pkcs11.constants.Attribute.PRIME`. """ DH_PKCS_DERIVE = 0x00000021 """ .. note:: Default mechanism for deriving shared keys from :attr:`KeyType.DH` private keys. This is the mechanism defined in PKCS #3. Takes the other participant's public key :attr:`pkcs11.constants.Attribute.VALUE` as the `mechanism_param`. """ X9_42_DH_KEY_PAIR_GEN = 0x00000030 X9_42_DH_DERIVE = 0x00000031 X9_42_DH_HYBRID_DERIVE = 0x00000032 X9_42_MQV_DERIVE = 0x00000033 _RC2_KEY_GEN = 0x00000100 _RC2_ECB = 0x00000101 _RC2_CBC = 0x00000102 _RC2_MAC = 0x00000103 _RC2_MAC_GENERAL = 0x00000104 _RC2_CBC_PAD = 0x00000105 _RC4_KEY_GEN = 0x00000110 _RC4 = 0x00000111 _DES_KEY_GEN = 0x00000120 _DES_ECB = 0x00000121 _DES_CBC = 0x00000122 _DES_MAC = 0x00000123 _DES_MAC_GENERAL = 0x00000124 _DES_CBC_PAD = 0x00000125 DES2_KEY_GEN = 0x00000130 """ .. note:: Default for generating DES2 keys. .. warning:: Considered insecure. Use AES where possible. """ DES3_KEY_GEN = 0x00000131 """ .. note:: Default for generating DES3 keys. .. warning:: Considered insecure. Use AES where possible. """ DES3_ECB = 0x00000132 """ .. note:: Default for key wrapping with DES2/3. .. warning:: Identical blocks will encipher to the same result. Considered insecure. Use AES where possible. """ DES3_CBC = 0x00000133 DES3_MAC = 0x00000134 """ .. note:: This is the default for signing/verification with :class:`KeyType.DES2` and :class:`KeyType.DES3`. .. warning:: Considered insecure. Use AES where possible. """ DES3_MAC_GENERAL = 0x00000135 DES3_CBC_PAD = 0x00000136 """ .. note:: Default for encryption/decryption with DES2/3. .. warning:: Considered insecure. Use AES where possible. """ DES3_CMAC_GENERAL = 0x00000137 DES3_CMAC = 0x00000138 _CDMF_KEY_GEN = 0x00000140 _CDMF_ECB = 0x00000141 _CDMF_CBC = 0x00000142 _CDMF_MAC = 0x00000143 _CDMF_MAC_GENERAL = 0x00000144 _CDMF_CBC_PAD = 0x00000145 _DES_OFB64 = 0x00000150 _DES_OFB8 = 0x00000151 _DES_CFB64 = 0x00000152 _DES_CFB8 = 0x00000153 _MD2 = 0x00000200 _MD2_HMAC = 0x00000201 _MD2_HMAC_GENERAL = 0x00000202 _MD5 = 0x00000210 _MD5_HMAC = 0x00000211 _MD5_HMAC_GENERAL = 0x00000212 SHA_1 = 0x00000220 """ .. warning:: SHA-1 is no longer considered secure. """ SHA_1_HMAC = 0x00000221 """ .. warning:: SHA-1 is no longer considered secure. """ SHA_1_HMAC_GENERAL = 0x00000222 """ .. warning:: SHA-1 is no longer considered secure. """ _RIPEMD128 = 0x00000230 _RIPEMD128_HMAC = 0x00000231 _RIPEMD128_HMAC_GENERAL = 0x00000232 _RIPEMD160 = 0x00000240 _RIPEMD160_HMAC = 0x00000241 _RIPEMD160_HMAC_GENERAL = 0x00000242 SHA256 = 0x00000250 SHA256_HMAC = 0x00000251 SHA256_HMAC_GENERAL = 0x00000252 SHA224 = 0x00000255 SHA224_HMAC = 0x00000256 SHA224_HMAC_GENERAL = 0x00000257 SHA384 = 0x00000260 SHA384_HMAC = 0x00000261 SHA384_HMAC_GENERAL = 0x00000262 SHA512 = 0x00000270 SHA512_HMAC = 0x00000271 SHA512_HMAC_GENERAL = 0x00000272 SECURID_KEY_GEN = 0x00000280 SECURID = 0x00000282 HOTP_KEY_GEN = 0x00000290 HOTP = 0x00000291 ACTI = 0x000002A0 ACTI_KEY_GEN = 0x000002A1 _CAST_KEY_GEN = 0x00000300 _CAST_ECB = 0x00000301 _CAST_CBC = 0x00000302 _CAST_MAC = 0x00000303 _CAST_MAC_GENERAL = 0x00000304 _CAST_CBC_PAD = 0x00000305 _CAST3_KEY_GEN = 0x00000310 _CAST3_ECB = 0x00000311 _CAST3_CBC = 0x00000312 _CAST3_MAC = 0x00000313 _CAST3_MAC_GENERAL = 0x00000314 _CAST3_CBC_PAD = 0x00000315 _CAST5_KEY_GEN = 0x00000320 _CAST128_KEY_GEN = 0x00000320 _CAST5_ECB = 0x00000321 _CAST128_ECB = 0x00000321 _CAST5_CBC = 0x00000322 _CAST128_CBC = 0x00000322 _CAST5_MAC = 0x00000323 _CAST128_MAC = 0x00000323 _CAST5_MAC_GENERAL = 0x00000324 _CAST128_MAC_GENERAL = 0x00000324 _CAST5_CBC_PAD = 0x00000325 _CAST128_CBC_PAD = 0x00000325 _RC5_KEY_GEN = 0x00000330 _RC5_ECB = 0x00000331 _RC5_CBC = 0x00000332 _RC5_MAC = 0x00000333 _RC5_MAC_GENERAL = 0x00000334 _RC5_CBC_PAD = 0x00000335 _IDEA_KEY_GEN = 0x00000340 _IDEA_ECB = 0x00000341 _IDEA_CBC = 0x00000342 _IDEA_MAC = 0x00000343 _IDEA_MAC_GENERAL = 0x00000344 _IDEA_CBC_PAD = 0x00000345 GENERIC_SECRET_KEY_GEN = 0x00000350 CONCATENATE_BASE_AND_KEY = 0x00000360 CONCATENATE_BASE_AND_DATA = 0x00000362 CONCATENATE_DATA_AND_BASE = 0x00000363 XOR_BASE_AND_DATA = 0x00000364 EXTRACT_KEY_FROM_KEY = 0x00000365 SSL3_PRE_MASTER_KEY_GEN = 0x00000370 SSL3_MASTER_KEY_DERIVE = 0x00000371 SSL3_KEY_AND_MAC_DERIVE = 0x00000372 SSL3_MASTER_KEY_DERIVE_DH = 0x00000373 SSL3_MD5_MAC = 0x00000380 SSL3_SHA1_MAC = 0x00000381 TLS_PRE_MASTER_KEY_GEN = 0x00000374 TLS_MASTER_KEY_DERIVE = 0x00000375 TLS_KEY_AND_MAC_DERIVE = 0x00000376 TLS_MASTER_KEY_DERIVE_DH = 0x00000377 TLS_PRF = 0x00000378 _MD5_KEY_DERIVATION = 0x00000390 _MD2_KEY_DERIVATION = 0x00000391 SHA1_KEY_DERIVATION = 0x00000392 SHA256_KEY_DERIVATION = 0x00000393 SHA384_KEY_DERIVATION = 0x00000394 SHA512_KEY_DERIVATION = 0x00000395 SHA224_KEY_DERIVATION = 0x00000396 _PBE_MD2_DES_CBC = 0x000003A0 _PBE_MD5_DES_CBC = 0x000003A1 _PBE_MD5_CAST_CBC = 0x000003A2 _PBE_MD5_CAST3_CBC = 0x000003A3 _PBE_MD5_CAST5_CBC = 0x000003A4 _PBE_MD5_CAST128_CBC = 0x000003A4 _PBE_SHA1_CAST5_CBC = 0x000003A5 _PBE_SHA1_CAST128_CBC = 0x000003A5 _PBE_SHA1_RC4_128 = 0x000003A6 _PBE_SHA1_RC4_40 = 0x000003A7 _PBE_SHA1_DES3_EDE_CBC = 0x000003A8 _PBE_SHA1_DES2_EDE_CBC = 0x000003A9 _PBE_SHA1_RC2_128_CBC = 0x000003AA _PBE_SHA1_RC2_40_CBC = 0x000003AB PKCS5_PBKD2 = 0x000003B0 _PBA_SHA1_WITH_SHA1_HMAC = 0x000003C0 WTLS_PRE_MASTER_KEY_GEN = 0x000003D0 WTLS_MASTER_KEY_DERIVE = 0x000003D1 WTLS_MASTER_KEY_DERIVE_DH_ECC = 0x000003D2 WTLS_PRF = 0x000003D3 WTLS_SERVER_KEY_AND_MAC_DERIVE = 0x000003D4 WTLS_CLIENT_KEY_AND_MAC_DERIVE = 0x000003D5 _KEY_WRAP_LYNKS = 0x00000400 _KEY_WRAP_SET_OAEP = 0x00000401 CMS_SIG = 0x00000500 KIP_DERIVE = 0x00000510 KIP_WRAP = 0x00000511 KIP_MAC = 0x00000512 _CAMELLIA_KEY_GEN = 0x00000550 _CAMELLIA_ECB = 0x00000551 _CAMELLIA_CBC = 0x00000552 _CAMELLIA_MAC = 0x00000553 _CAMELLIA_MAC_GENERAL = 0x00000554 _CAMELLIA_CBC_PAD = 0x00000555 _CAMELLIA_ECB_ENCRYPT_DATA = 0x00000556 _CAMELLIA_CBC_ENCRYPT_DATA = 0x00000557 _CAMELLIA_CTR = 0x00000558 _ARIA_KEY_GEN = 0x00000560 _ARIA_ECB = 0x00000561 _ARIA_CBC = 0x00000562 _ARIA_MAC = 0x00000563 _ARIA_MAC_GENERAL = 0x00000564 _ARIA_CBC_PAD = 0x00000565 _ARIA_ECB_ENCRYPT_DATA = 0x00000566 _ARIA_CBC_ENCRYPT_DATA = 0x00000567 SEED_KEY_GEN = 0x00000650 SEED_ECB = 0x00000651 """ .. warning:: Identical blocks will encipher to the same result. """ SEED_CBC = 0x00000652 SEED_MAC = 0x00000653 SEED_MAC_GENERAL = 0x00000654 SEED_CBC_PAD = 0x00000655 SEED_ECB_ENCRYPT_DATA = 0x00000656 SEED_CBC_ENCRYPT_DATA = 0x00000657 _SKIPJACK_KEY_GEN = 0x00001000 _SKIPJACK_ECB64 = 0x00001001 _SKIPJACK_CBC64 = 0x00001002 _SKIPJACK_OFB64 = 0x00001003 _SKIPJACK_CFB64 = 0x00001004 _SKIPJACK_CFB32 = 0x00001005 _SKIPJACK_CFB16 = 0x00001006 _SKIPJACK_CFB8 = 0x00001007 _SKIPJACK_WRAP = 0x00001008 _SKIPJACK_PRIVATE_WRAP = 0x00001009 _SKIPJACK_RELAYX = 0x0000100a _KEA_KEY_PAIR_GEN = 0x00001010 _KEA_KEY_DERIVE = 0x00001011 _FORTEZZA_TIMESTAMP = 0x00001020 _BATON_KEY_GEN = 0x00001030 _BATON_ECB128 = 0x00001031 _BATON_ECB96 = 0x00001032 _BATON_CBC128 = 0x00001033 _BATON_COUNTER = 0x00001034 _BATON_SHUFFLE = 0x00001035 _BATON_WRAP = 0x00001036 EC_KEY_PAIR_GEN = 0x00001040 """ .. note:: Default mechanism for generating :attr:`KeyType.EC` key pairs Requires :class:`pkcs11.DomainParameters` of :attr:`pkcs11.constants.Attribute.EC_PARAMS`. """ ECDSA = 0x00001041 """ECDSA with no hashing. Input truncated to 1024-bits.""" ECDSA_SHA1 = 0x00001042 """ .. warning:: SHA-1 is no longer considered secure. """ ECDSA_SHA224 = 0x00001043 ECDSA_SHA256 = 0x00001044 ECDSA_SHA384 = 0x00001045 ECDSA_SHA512 = 0x00001046 """ ECDSA with SHA512 hashing. .. note:: Default for signing/verification with :attr:`KeyType.EC` keys. """ ECDH1_DERIVE = 0x00001050 """ .. note:: Default mechanism for deriving shared keys from :attr:`KeyType.EC` private keys. Takes a tuple of: * key derivation function (:class:`pkcs11.mechanisms.KDF`); * shared value (:class:`bytes`); and * other participant's :attr:`pkcs11.constants.Attribute.EC_POINT` (:class:`bytes`) as the `mechanism_param`. """ ECDH1_COFACTOR_DERIVE = 0x00001051 ECMQV_DERIVE = 0x00001052 _JUNIPER_KEY_GEN = 0x00001060 _JUNIPER_ECB128 = 0x00001061 _JUNIPER_CBC128 = 0x00001062 _JUNIPER_COUNTER = 0x00001063 _JUNIPER_SHUFFLE = 0x00001064 _JUNIPER_WRAP = 0x00001065 _FASTHASH = 0x00001070 AES_KEY_GEN = 0x00001080 """ .. note:: Default for generating :attr:`KeyType.AES` keys. """ AES_ECB = 0x00001081 """ .. note:: Default wrapping mechanism for :attr:`KeyType.AES` keys. .. warning:: Identical blocks will encipher to the same result. """ AES_CBC = 0x00001082 AES_CBC_PAD = 0x00001085 """ CBC with PKCS#7 padding to pad files to a whole number of blocks. .. note:: Default for encrypting/decrypting with :attr:`KeyType.AES` keys. Requires a 128-bit initialisation vector passed as `mechanism_param`. """ AES_CTR = 0x00001086 AES_CTS = 0x00001089 AES_MAC = 0x00001083 """ .. note:: This is the default for signing/verification with :class:`KeyType.AES`. """ AES_MAC_GENERAL = 0x00001084 AES_CMAC = 0x0000108A AES_CMAC_GENERAL = 0x0000108B BLOWFISH_KEY_GEN = 0x00001090 BLOWFISH_CBC = 0x00001091 BLOWFISH_CBC_PAD = 0x00001094 TWOFISH_KEY_GEN = 0x00001092 TWOFISH_CBC = 0x00001093 TWOFISH_CBC_PAD = 0x00001095 AES_GCM = 0x00001087 AES_CCM = 0x00001088 _AES_KEY_WRAP = 0x00001090 """This is the old value for AES_KEY_WRAP. Changed in the 2016 spec.""" _AES_KEY_WRAP_PAD = 0x00001091 """This is the old value for AES_KEY_WRAP_PAD. Changed in the 2016 spec.""" AES_XCBC_MAC = 0x0000108C AES_XCBC_MAC_96 = 0x0000108D AES_GMAC = 0x0000108E AES_OFB = 0x00002104 AES_CFB64 = 0x00002105 AES_CFB8 = 0x00002106 AES_CFB128 = 0x00002107 AES_CFB1 = 0x00002108 AES_KEY_WRAP = 0x00002109 AES_KEY_WRAP_PAD = 0x0000210A DES_ECB_ENCRYPT_DATA = 0x00001100 DES_CBC_ENCRYPT_DATA = 0x00001101 DES3_ECB_ENCRYPT_DATA = 0x00001102 DES3_CBC_ENCRYPT_DATA = 0x00001103 AES_ECB_ENCRYPT_DATA = 0x00001104 AES_CBC_ENCRYPT_DATA = 0x00001105 GOSTR3410_KEY_PAIR_GEN = 0x00001200 GOSTR3410 = 0x00001201 GOSTR3410_WITH_GOSTR3411 = 0x00001202 GOSTR3410_KEY_WRAP = 0x00001203 GOSTR3410_DERIVE = 0x00001204 GOSTR3411 = 0x00001210 GOSTR3411_HMAC = 0x00001211 GOST28147_KEY_GEN = 0x00001220 GOST28147_ECB = 0x00001221 """ .. warning:: Identical blocks will encipher to the same result. """ GOST28147 = 0x00001222 GOST28147_MAC = 0x00001223 GOST28147_KEY_WRAP = 0x00001224 DSA_PARAMETER_GEN = 0x00002000 """ .. note:: Default mechanism for generating :attr:`KeyType.DSA` domain parameters. """ DH_PKCS_PARAMETER_GEN = 0x00002001 """ .. note:: Default mechanism for generating :attr:`KeyType.DH` domain parameters. This is the mechanism defined in PKCS #3. """ X9_42_DH_PARAMETER_GEN = 0x00002002 """ .. note:: Default mechanism for generating :attr:`KeyType.X9_42_DH` domain parameters (X9.42 DH). """ # from version 3.0 EDDSA = 0x00001057 EC_EDWARDS_KEY_PAIR_GEN = 0x00001055 _VENDOR_DEFINED = 0x80000000 def __repr__(self): return '' % self.name class KDF(IntEnum): """ Key Derivation Functions. """ NULL = 0x00000001 SHA1 = 0x00000002 SHA1_ASN1 = 0x00000003 SHA1_CONCATENATE = 0x00000004 SHA224 = 0x00000005 SHA256 = 0x00000006 SHA384 = 0x00000007 SHA512 = 0x00000008 CPDIVERSIFY = 0x00000009 def __repr__(self): return '' % self.name class MGF(IntEnum): """ RSA PKCS #1 Mask Generation Functions. """ SHA1 = 0x00000001 SHA256 = 0x00000002 SHA384 = 0x00000003 SHA512 = 0x00000004 SHA224 = 0x00000005 def __repr__(self): return '' % self.name python-pkcs11-0.7.0/pkcs11/constants.py0000664000372000037200000003501413717606207020505 0ustar travistravis00000000000000""" PKCS#11 constants. See the Python :mod:`enum` documentation for more information on how to use these classes. """ try: from enum import IntEnum, IntFlag, unique except ImportError: from aenum import IntEnum, IntFlag, unique DEFAULT = object() """Sentinel value used in templates. Not all pkcs11 attribute sets are accepted by HSMs. Use this value to remove the attribute from the template sent to the HSM or to use the HSM default value. """ @unique class UserType(IntEnum): """PKCS#11 user types.""" NOBODY = 999 """ Not officially in the PKCS#11 spec. Used to represent a session that is not logged in. """ SO = 0 """Security officer.""" USER = 1 class ObjectClass(IntEnum): """ PKCS#11 :class:`Object` class. This is the type of object we have. """ DATA = 0x00000000 CERTIFICATE = 0x00000001 """See :class:`pkcs11.Certificate`.""" PUBLIC_KEY = 0x00000002 """See :class:`pkcs11.PublicKey`.""" PRIVATE_KEY = 0x00000003 """See :class:`pkcs11.PrivateKey`.""" SECRET_KEY = 0x00000004 """See :class:`pkcs11.SecretKey`.""" HW_FEATURE = 0x00000005 DOMAIN_PARAMETERS = 0x00000006 """See :class:`pkcs11.DomainParameters`.""" MECHANISM = 0x00000007 OTP_KEY = 0x00000008 _VENDOR_DEFINED = 0x80000000 def __repr__(self): return '' % self.name _ARRAY_ATTRIBUTE = 0x40000000 """Attribute consists of an array of values.""" class Attribute(IntEnum): """ PKCS#11 object attributes. Not all attributes are relevant to all objects. Relevant attributes for each object type are given in `PKCS #11 `_. """ CLASS = 0x00000000 """Object type (:class:`ObjectClass`).""" TOKEN = 0x00000001 """ If True object will be stored to token. Otherwise has session lifetime (:class:`bool`). """ PRIVATE = 0x00000002 """ True if user must be authenticated to access this object (:class:`bool`). """ LABEL = 0x00000003 """Object label (:class:`str`).""" APPLICATION = 0x00000010 VALUE = 0x00000011 """ Object value. Usually represents a secret or private key. For certificates this is the complete certificate in the certificate's native format (e.g. BER-encoded X.509 or WTLS encoding). May be `SENSITIVE` (:class:`bytes`). """ OBJECT_ID = 0x00000012 CERTIFICATE_TYPE = 0x00000080 """ Certificate type (:class:`CertificateType`). """ ISSUER = 0x00000081 """ Certificate issuer in certificate's native format (e.g. X.509 DER-encoding or WTLS encoding) (:class:`bytes`). """ SERIAL_NUMBER = 0x00000082 """ Certificate serial number in certificate's native format (e.g. X.509 DER-encoding) (:class:`bytes`). """ AC_ISSUER = 0x00000083 """ Attribute Certificate Issuer. Different from `ISSUER` because the encoding is different (:class:`bytes`). """ OWNER = 0x00000084 """ Attribute Certificate Owner. Different from `SUBJECT` because the encoding is different (:class:`bytes`). """ ATTR_TYPES = 0x00000085 """ BER-encoding of a sequence of object identifier values corresponding to the attribute types contained in the certificate. When present, this field offers an opportunity for applications to search for a particular attribute certificate without fetching and parsing the certificate itself. """ TRUSTED = 0x00000086 """ This key can be used to wrap keys with `WRAP_WITH_TRUSTED` set; or this certificate can be trusted. (:class:`bool`). """ CERTIFICATE_CATEGORY = 0x00000087 """ Certificate category (:class:`CertificateCategory`). """ JAVA_MIDP_SECURITY_DOMAIN = 0x00000088 URL = 0x00000089 """URL where the complete certificate can be obtained.""" HASH_OF_SUBJECT_PUBLIC_KEY = 0x0000008A """Hash of the certificate subject's public key.""" HASH_OF_ISSUER_PUBLIC_KEY = 0x0000008B """Hash of the certificate issuer's public key.""" CHECK_VALUE = 0x00000090 """`VALUE` checksum. Key Check Value (:class:`bytes`).""" KEY_TYPE = 0x00000100 """Key type (:class:`KeyType`).""" SUBJECT = 0x00000101 """ Certificate subject in certificate's native format (e.g. X.509 DER-encoding or WTLS encoding) (:class:`bytes`). """ ID = 0x00000102 """Key ID (bytes).""" SENSITIVE = 0x00000103 """ Sensitive attributes cannot be retrieved from the HSM (e.g. `VALUE` or `PRIVATE_EXPONENT`) (:class:`bool`). """ ENCRYPT = 0x00000104 """Key supports encryption (:class:`bool`).""" DECRYPT = 0x00000105 """Key supports decryption (:class:`bool`).""" WRAP = 0x00000106 """Key supports wrapping (:class:`bool`).""" UNWRAP = 0x00000107 """Key supports unwrapping (:class:`bool`).""" SIGN = 0x00000108 """Key supports signing (:class:`bool`).""" SIGN_RECOVER = 0x00000109 VERIFY = 0x0000010A """Key supports signature verification (:class:`bool`).""" VERIFY_RECOVER = 0x0000010B DERIVE = 0x0000010C """Key supports key derivation (:class:`bool`).""" START_DATE = 0x00000110 """Start date for the object's validity (:class:`datetime.date`).""" END_DATE = 0x00000111 """End date for the object's validity (:class:`datetime.date`).""" MODULUS = 0x00000120 """RSA private key modulus (n) (`biginteger` as :class:`bytes`).""" MODULUS_BITS = 0x00000121 """ RSA private key modulus length. Use this for private key generation (:class:`int`). """ PUBLIC_EXPONENT = 0x00000122 """ RSA public exponent (e) (`biginteger` as :class:`bytes`). Default is b'\1\0\1' (65537). """ PRIVATE_EXPONENT = 0x00000123 """RSA private exponent (d) (`biginteger` as :class:`bytes`).""" PRIME_1 = 0x00000124 """ RSA private key prime #1 (p). May not be stored. (`biginteger` as :class:`bytes`). """ PRIME_2 = 0x00000125 """ RSA private key prime #2 (q). May not be stored. (`biginteger` as :class:`bytes`). """ EXPONENT_1 = 0x00000126 """ RSA private key exponent #1 (d mod p-1). May not be stored. (`biginteger` as :class:`bytes`). """ EXPONENT_2 = 0x00000127 """ RSA private key exponent #2 (d mod q-1). May not be stored. (`biginteger` as :class:`bytes`). """ COEFFICIENT = 0x00000128 """ RSA private key CRT coefficient (q^-1 mod p). May not be stored. (`biginteger` as :class:`bytes`). """ PRIME = 0x00000130 """ Prime number 'q' (used for DH). (`biginteger` as :class:`bytes`). """ SUBPRIME = 0x00000131 """ Subprime number 'q' (used for DH). (`biginteger` as :class:`bytes`). """ BASE = 0x00000132 """ Base number 'g' (used for DH). (`biginteger` as :class:`bytes`). """ PRIME_BITS = 0x00000133 SUBPRIME_BITS = 0x00000134 VALUE_BITS = 0x00000160 VALUE_LEN = 0x00000161 """ `VALUE` length in bytes. Use this for secret key generation (:class:`int`). """ EXTRACTABLE = 0x00000162 """Key can be extracted wrapped.""" LOCAL = 0x00000163 """True if generated on the token, False if imported.""" NEVER_EXTRACTABLE = 0x00000164 """`EXTRACTABLE` has always been False.""" ALWAYS_SENSITIVE = 0x00000165 """`SENSITIVE` has always been True.""" KEY_GEN_MECHANISM = 0x00000166 """Key generation mechanism (:class:`pkcs11.mechanisms.Mechanism`).""" MODIFIABLE = 0x00000170 """Object can be modified (:class:`bool`).""" COPYABLE = 0x00000171 """Object can be copied (:class:`bool`).""" EC_PARAMS = 0x00000180 """ DER-encoded ANSI X9.62 Elliptic-Curve domain parameters (:class:`bytes`). These can packed using :mod:`pkcs11.util.ec.encode_named_curve_parameters`: :: from pkcs11.util.ec import encode_named_curve_parameters ecParams = encode_named_curve_parameters('secp256r1') Or output by OpenSSL: :: openssl ecparam -outform der -name | base64 """ EC_POINT = 0x00000181 """ DER-encoded ANSI X9.62 Public key for :attr:`KeyType.EC` (:class:`bytes`). """ SECONDARY_AUTH = 0x00000200 AUTH_PIN_FLAGS = 0x00000201 ALWAYS_AUTHENTICATE = 0x00000202 """ User has to provide pin with each use (sign or decrypt) (:class:`bool`). """ WRAP_WITH_TRUSTED = 0x00000210 """Key can only be wrapped with a `TRUSTED` key.""" WRAP_TEMPLATE = (_ARRAY_ATTRIBUTE | 0x00000211) UNWRAP_TEMPLATE = (_ARRAY_ATTRIBUTE | 0x00000212) DERIVE_TEMPLATE = (_ARRAY_ATTRIBUTE | 0x00000213) OTP_FORMAT = 0x00000220 OTP_LENGTH = 0x00000221 OTP_TIME_INTERVAL = 0x00000222 OTP_USER_FRIENDLY_MODE = 0x00000223 OTP_CHALLENGE_REQUIREMENT = 0x00000224 OTP_TIME_REQUIREMENT = 0x00000225 OTP_COUNTER_REQUIREMENT = 0x00000226 OTP_PIN_REQUIREMENT = 0x00000227 OTP_COUNTER = 0x0000022E OTP_TIME = 0x0000022F OTP_USER_IDENTIFIER = 0x0000022A OTP_SERVICE_IDENTIFIER = 0x0000022B OTP_SERVICE_LOGO = 0x0000022C OTP_SERVICE_LOGO_TYPE = 0x0000022D GOSTR3410_PARAMS = 0x00000250 GOSTR3411_PARAMS = 0x00000251 GOST28147_PARAMS = 0x00000252 HW_FEATURE_TYPE = 0x00000300 RESET_ON_INIT = 0x00000301 HAS_RESET = 0x00000302 PIXEL_X = 0x00000400 PIXEL_Y = 0x00000401 RESOLUTION = 0x00000402 CHAR_ROWS = 0x00000403 CHAR_COLUMNS = 0x00000404 COLOR = 0x00000405 BITS_PER_PIXEL = 0x00000406 CHAR_SETS = 0x00000480 ENCODING_METHODS = 0x00000481 MIME_TYPES = 0x00000482 MECHANISM_TYPE = 0x00000500 REQUIRED_CMS_ATTRIBUTES = 0x00000501 DEFAULT_CMS_ATTRIBUTES = 0x00000502 SUPPORTED_CMS_ATTRIBUTES = 0x00000503 ALLOWED_MECHANISMS = (_ARRAY_ATTRIBUTE | 0x00000600) _VENDOR_DEFINED = 0x80000000 def __repr__(self): return '' % self.name class CertificateType(IntEnum): """ Certificate type of a :class:`pkcs11.Certificate`. """ X_509 = 0x00000000 X_509_ATTR_CERT = 0x00000001 WTLS = 0x00000002 _VENDOR_DEFINED = 0x80000000 @unique class MechanismFlag(IntFlag): """ Describes the capabilities of a :class:`pkcs11.mechanisms.Mechanism` or :class:`pkcs11.Object`. Some objects and mechanisms are symmetric (i.e. can be used for encryption and decryption), some are asymmetric (e.g. public key cryptography). """ HW = 0x00000001 """Mechanism is performed in hardware.""" ENCRYPT = 0x00000100 """Can be used for encryption.""" DECRYPT = 0x00000200 """Can be used for decryption.""" DIGEST = 0x00000400 """Can make a message digest (hash).""" SIGN = 0x00000800 """Can calculate digital signature.""" SIGN_RECOVER = 0x00001000 VERIFY = 0x00002000 """Can verify digital signature.""" VERIFY_RECOVER = 0x00004000 GENERATE = 0x00008000 """Can generate key/object.""" GENERATE_KEY_PAIR = 0x00010000 """Can generate key pair.""" WRAP = 0x00020000 """Can wrap a key for export.""" UNWRAP = 0x00040000 """Can unwrap a key for import.""" DERIVE = 0x00080000 """Can derive a key from another key.""" EC_F_P = 0x00100000 EC_F_2M = 0x00200000 EC_ECPARAMETERS = 0x00400000 EC_NAMEDCURVE = 0x00800000 EC_UNCOMPRESS = 0x01000000 EC_COMPRESS = 0x02000000 EXTENSION = 0x80000000 @unique class SlotFlag(IntFlag): """:class:`pkcs11.Slot` flags.""" TOKEN_PRESENT = 0x00000001 """ A token is present in the slot (N.B. some hardware known not to set this for soft-tokens.) """ REMOVABLE_DEVICE = 0x00000002 """Removable devices.""" HW_SLOT = 0x00000004 """Hardware slot.""" @unique class TokenFlag(IntFlag): """:class:`pkcs11.Token` flags.""" RNG = 0x00000001 """Has random number generator.""" WRITE_PROTECTED = 0x00000002 """Token is write protected.""" LOGIN_REQUIRED = 0x00000004 """User must login.""" USER_PIN_INITIALIZED = 0x00000008 """Normal user's pin is set.""" RESTORE_KEY_NOT_NEEDED = 0x00000020 """ If it is set, that means that *every* time the state of cryptographic operations of a session is successfully saved, all keys needed to continue those operations are stored in the state. """ CLOCK_ON_TOKEN = 0x00000040 """ If it is set, that means that the token has some sort of clock. The time on that clock is returned in the token info structure. """ PROTECTED_AUTHENTICATION_PATH = 0x00000100 """ If it is set, that means that there is some way for the user to login without sending a PIN through the Cryptoki library itself. """ DUAL_CRYPTO_OPERATIONS = 0x00000200 """ If it is true, that means that a single session with the token can perform dual simultaneous cryptographic operations (digest and encrypt; decrypt and digest; sign and encrypt; and decrypt and sign). """ TOKEN_INITIALIZED = 0x00000400 """ If it is true, the token has been initialized using C_InitializeToken or an equivalent mechanism outside the scope of PKCS #11. Calling C_InitializeToken when this flag is set will cause the token to be reinitialized. """ USER_PIN_COUNT_LOW = 0x00010000 """ If it is true, an incorrect user login PIN has been entered at least once since the last successful authentication. """ USER_PIN_FINAL_TRY = 0x00020000 """ If it is true, supplying an incorrect user PIN will it to become locked. """ USER_PIN_LOCKED = 0x00040000 """ If it is true, the user PIN has been locked. User login to the token is not possible. """ USER_PIN_TO_BE_CHANGED = 0x00080000 """ If it is true, the user PIN value is the default value set by token initialization or manufacturing, or the PIN has been expired by the card. """ SO_PIN_COUNT_LOW = 0x00100000 """ If it is true, an incorrect SO (security officer) login PIN has been entered at least once since the last successful authentication. """ SO_PIN_FINAL_TRY = 0x00200000 """ If it is true, supplying an incorrect SO (security officer) PIN will it to become locked. """ SO_PIN_LOCKED = 0x00400000 """ If it is true, the SO (security officer) PIN has been locked. SO login to the token is not possible. """ SO_PIN_TO_BE_CHANGED = 0x00800000 """ If it is true, the SO PIN value is the default value set by token initialization or manufacturing, or the PIN has been expired by the card. """ ERROR_STATE = 0x01000000 python-pkcs11-0.7.0/pkcs11/util/0000775000372000037200000000000013717606456017077 5ustar travistravis00000000000000python-pkcs11-0.7.0/pkcs11/util/rsa.py0000664000372000037200000000547713717606207020245 0ustar travistravis00000000000000""" Key handling utilities for RSA keys (PKCS#1). """ from asn1crypto.keys import RSAPrivateKey, RSAPublicKey from . import biginteger from ..constants import Attribute, ObjectClass, MechanismFlag from ..mechanisms import KeyType from ..defaults import DEFAULT_KEY_CAPABILITIES def decode_rsa_private_key(der, capabilities=None): """ Decode a RFC2437 (PKCS#1) DER-encoded RSA private key into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. :param bytes der: DER-encoded key :param MechanismFlag capabilities: Optional key capabilities :rtype: dict(Attribute,*) """ if capabilities is None: capabilities = DEFAULT_KEY_CAPABILITIES[KeyType.RSA] key = RSAPrivateKey.load(der) return { Attribute.CLASS: ObjectClass.PRIVATE_KEY, Attribute.KEY_TYPE: KeyType.RSA, Attribute.MODULUS: biginteger(key['modulus']), Attribute.PUBLIC_EXPONENT: biginteger(key['public_exponent']), Attribute.PRIVATE_EXPONENT: biginteger(key['private_exponent']), Attribute.PRIME_1: biginteger(key['prime1']), Attribute.PRIME_2: biginteger(key['prime2']), Attribute.EXPONENT_1: biginteger(key['exponent1']), Attribute.EXPONENT_2: biginteger(key['exponent2']), Attribute.COEFFICIENT: biginteger(key['coefficient']), Attribute.DECRYPT: MechanismFlag.DECRYPT in capabilities, Attribute.SIGN: MechanismFlag.SIGN in capabilities, Attribute.UNWRAP: MechanismFlag.UNWRAP in capabilities, } def decode_rsa_public_key(der, capabilities=None): """ Decode a RFC2437 (PKCS#1) DER-encoded RSA public key into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. :param bytes der: DER-encoded key :param MechanismFlag capabilities: Optional key capabilities :rtype: dict(Attribute,*) """ if capabilities is None: capabilities = DEFAULT_KEY_CAPABILITIES[KeyType.RSA] key = RSAPublicKey.load(der) return { Attribute.CLASS: ObjectClass.PUBLIC_KEY, Attribute.KEY_TYPE: KeyType.RSA, Attribute.MODULUS: biginteger(key['modulus']), Attribute.PUBLIC_EXPONENT: biginteger(key['public_exponent']), Attribute.ENCRYPT: MechanismFlag.ENCRYPT in capabilities, Attribute.VERIFY: MechanismFlag.VERIFY in capabilities, Attribute.WRAP: MechanismFlag.WRAP in capabilities, } def encode_rsa_public_key(key): """ Encode an RSA public key into PKCS#1 DER-encoded format. :param PublicKey key: RSA public key :rtype: bytes """ return RSAPublicKey({ 'modulus': int.from_bytes(key[Attribute.MODULUS], byteorder='big'), 'public_exponent': int.from_bytes(key[Attribute.PUBLIC_EXPONENT], byteorder='big'), }).dump() python-pkcs11-0.7.0/pkcs11/util/dh.py0000664000372000037200000000302313717606207020034 0ustar travistravis00000000000000""" Key handling utilities for Diffie-Hellman keys. """ from asn1crypto.algos import DHParameters from asn1crypto.core import Integer from . import biginteger from ..constants import Attribute from ..exceptions import AttributeTypeInvalid def decode_dh_domain_parameters(der): """ Decode DER-encoded Diffie-Hellman domain parameters. :param bytes der: DER-encoded parameters :rtype: dict(Attribute,*) """ params = DHParameters.load(der) return { Attribute.BASE: biginteger(params['g']), Attribute.PRIME: biginteger(params['p']), } def encode_dh_domain_parameters(obj): """ Encode DH domain parameters into DER-encoded format. Calculates the subprime if it isn't available. :param DomainParameters obj: domain parameters :rtype: bytes """ asn1 = DHParameters({ 'g': int.from_bytes(obj[Attribute.BASE], byteorder='big'), 'p': int.from_bytes(obj[Attribute.PRIME], byteorder='big'), }) return asn1.dump() def encode_dh_public_key(key): """ Encode DH public key into RFC 3279 DER-encoded format. :param PublicKey key: public key :rtype: bytes """ asn1 = Integer(int.from_bytes(key[Attribute.VALUE], byteorder='big')) return asn1.dump() def decode_dh_public_key(der): """ Decode a DH public key from RFC 3279 DER-encoded format. Returns a `biginteger` encoded as bytes. :param bytes der: DER-encoded public key :rtype: bytes """ asn1 = Integer.load(der) return biginteger(asn1) python-pkcs11-0.7.0/pkcs11/util/x509.py0000664000372000037200000000656213717606207020161 0ustar travistravis00000000000000""" Certificate handling utilities for X.509 (SSL) certificates. """ from asn1crypto.x509 import Certificate from ..constants import Attribute, ObjectClass, CertificateType from ..mechanisms import KeyType def decode_x509_public_key(der): """ Decode a DER-encoded X.509 certificate's public key into a set of attributes able to be passed to :meth:`pkcs11.Session.create_object`. For PEM-encoded certificates, use :func:`asn1crypto.pem.unarmor`. .. warning:: Does not verify certificate. :param bytes der: DER-encoded certificate :rtype: dict(Attribute,*) """ x509 = Certificate.load(der) key_info = x509.public_key key = bytes(key_info['public_key']) key_type = { 'rsa': KeyType.RSA, 'dsa': KeyType.DSA, 'ec': KeyType.EC, }[key_info.algorithm] attrs = { Attribute.CLASS: ObjectClass.PUBLIC_KEY, Attribute.KEY_TYPE: key_type, } if key_type is KeyType.RSA: from .rsa import decode_rsa_public_key attrs.update(decode_rsa_public_key(key)) elif key_type is KeyType.DSA: from .dsa import decode_dsa_domain_parameters, decode_dsa_public_key params = key_info['algorithm']['parameters'].dump() attrs.update(decode_dsa_domain_parameters(params)) attrs.update({ Attribute.VALUE: decode_dsa_public_key(key), }) elif key_type is KeyType.EC: params = key_info['algorithm']['parameters'].dump() attrs.update({ Attribute.EC_PARAMS: params, Attribute.EC_POINT: key, }) else: raise AssertionError("Should not be reached") return attrs def decode_x509_certificate(der, extended_set=False): """ Decode a DER-encoded X.509 certificate into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. Optionally pass `extended_set` to include additional attributes: start date, end date and key identifiers. For PEM-encoded certificates, use :func:`asn1crypto.pem.unarmor`. .. warning:: Does not verify certificate. :param bytes der: DER-encoded certificate :param extended_set: decodes more metadata about the certificate :rtype: dict(Attribute,*) """ x509 = Certificate.load(der) subject = x509.subject issuer = x509.issuer serial = x509['tbs_certificate']['serial_number'] template = { Attribute.CLASS: ObjectClass.CERTIFICATE, Attribute.CERTIFICATE_TYPE: CertificateType.X_509, Attribute.SUBJECT: subject.dump(), Attribute.ISSUER: issuer.dump(), Attribute.SERIAL_NUMBER: serial.dump(), Attribute.VALUE: x509.dump(), } if extended_set: start_date = \ x509['tbs_certificate']['validity']['not_before'].native.date() end_date = \ x509['tbs_certificate']['validity']['not_after'].native.date() template.update({ Attribute.START_DATE: start_date, Attribute.END_DATE: end_date, }) # FIXME: is this correct? try: template[Attribute.HASH_OF_SUBJECT_PUBLIC_KEY] = \ x509.key_identifier except KeyError: pass try: template[Attribute.HASH_OF_ISSUER_PUBLIC_KEY] = \ x509.authority_key_identifier except KeyError: pass return template python-pkcs11-0.7.0/pkcs11/util/dsa.py0000664000372000037200000000425213717606207020215 0ustar travistravis00000000000000""" Key handling utilities for DSA keys, domain parameters and signatures.. """ from asn1crypto.core import Integer from asn1crypto.keys import DSAParams from asn1crypto.algos import DSASignature from . import biginteger from ..constants import Attribute def decode_dsa_domain_parameters(der): """ Decode RFC 3279 DER-encoded Dss-Params. :param bytes der: DER-encoded parameters :rtype: dict(Attribute,*) """ params = DSAParams.load(der) return { Attribute.BASE: biginteger(params['g']), Attribute.PRIME: biginteger(params['p']), Attribute.SUBPRIME: biginteger(params['q']), } def encode_dsa_domain_parameters(obj): """ Encode RFC 3279 DER-encoded Dss-Params. :param DomainParameters obj: domain parameters :rtype: bytes """ asn1 = DSAParams({ 'g': int.from_bytes(obj[Attribute.BASE], byteorder='big'), 'p': int.from_bytes(obj[Attribute.PRIME], byteorder='big'), 'q': int.from_bytes(obj[Attribute.SUBPRIME], byteorder='big'), }) return asn1.dump() def encode_dsa_public_key(key): """ Encode DSA public key into RFC 3279 DER-encoded format. :param PublicKey key: public key :rtype: bytes """ asn1 = Integer(int.from_bytes(key[Attribute.VALUE], byteorder='big')) return asn1.dump() def decode_dsa_public_key(der): """ Decode a DSA public key from RFC 3279 DER-encoded format. Returns a `biginteger` encoded as bytes. :param bytes der: DER-encoded public key :rtype: bytes """ asn1 = Integer.load(der) return biginteger(asn1) def encode_dsa_signature(signature): """ Encode a signature (generated by :meth:`pkcs11.SignMixin.sign`) into DER-encoded ASN.1 (Dss_Sig_Value) format. :param bytes signature: signature as bytes :rtype: bytes """ asn1 = DSASignature.from_p1363(signature) return asn1.dump() def decode_dsa_signature(der): """ Decode a DER-encoded ASN.1 (Dss_Sig_Value) signature (as generated by OpenSSL/X.509) into PKCS #11 format. :param bytes der: DER-encoded signature :rtype bytes: """ asn1 = DSASignature.load(der) return asn1.to_p1363() python-pkcs11-0.7.0/pkcs11/util/__init__.py0000664000372000037200000000057113717606207021205 0ustar travistravis00000000000000def biginteger(value): """ Returns a PKCS#11 biginteger bytestream from a Python integer or similar type (e.g. :class:`asn1crypto.core.Integer`). :param int value: Value :rtype: bytes """ value = int(value) # In case it's a asn1 type or similar return value.to_bytes((value.bit_length() + 7) // 8, byteorder='big') python-pkcs11-0.7.0/pkcs11/util/ec.py0000664000372000037200000000671613717606207020044 0ustar travistravis00000000000000""" Key handling utilities for EC keys (ANSI X.62/RFC3279), domain parameter and signatures. """ from asn1crypto.keys import ( ECDomainParameters, ECPrivateKey, NamedCurve, PublicKeyInfo, ) from asn1crypto.algos import DSASignature from asn1crypto.core import OctetString from ..constants import Attribute, ObjectClass from ..mechanisms import KeyType def encode_named_curve_parameters(oid): """ Return DER-encoded ANSI X.62 EC parameters for a named curve. Curve names are given by object identifier or common name. Names come from `asn1crypto `_. :param str oid: OID or named curve :rtype: bytes """ return ECDomainParameters( name='named', value=NamedCurve.unmap(oid), ).dump() def decode_ec_public_key(der, encode_ec_point=True): """ Decode a DER-encoded EC public key as stored by OpenSSL into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. .. note:: **encode_ec_point** For use as an attribute `EC_POINT` should be DER-encoded (True). For key derivation implementations can vary. Since v2.30 the specification says implementations MUST accept a raw `EC_POINT` for ECDH (False), however not all implementations follow this yet. :param bytes der: DER-encoded key :param encode_ec_point: See text. :rtype: dict(Attribute,*) """ asn1 = PublicKeyInfo.load(der) assert asn1.algorithm == 'ec', \ "Wrong algorithm, not an EC key!" ecpoint = bytes(asn1['public_key']) if encode_ec_point: ecpoint = OctetString(ecpoint).dump() return { Attribute.KEY_TYPE: KeyType.EC, Attribute.CLASS: ObjectClass.PUBLIC_KEY, Attribute.EC_PARAMS: asn1['algorithm']['parameters'].dump(), Attribute.EC_POINT: ecpoint, } def decode_ec_private_key(der): """ Decode a DER-encoded EC private key as stored by OpenSSL into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. :param bytes der: DER-encoded key :rtype: dict(Attribute,*) """ asn1 = ECPrivateKey.load(der) return { Attribute.KEY_TYPE: KeyType.EC, Attribute.CLASS: ObjectClass.PRIVATE_KEY, Attribute.EC_PARAMS: asn1['parameters'].chosen.dump(), Attribute.VALUE: asn1['private_key'].contents, } def encode_ec_public_key(key): """ Encode a DER-encoded EC public key as stored by OpenSSL. :param PublicKey key: EC public key :rtype: bytes """ ecparams = ECDomainParameters.load(key[Attribute.EC_PARAMS]) ecpoint = bytes(OctetString.load(key[Attribute.EC_POINT])) return PublicKeyInfo({ 'algorithm': { 'algorithm': 'ec', 'parameters': ecparams, }, 'public_key': ecpoint, }).dump() def encode_ecdsa_signature(signature): """ Encode a signature (generated by :meth:`pkcs11.SignMixin.sign`) into DER-encoded ASN.1 (ECDSA_Sig_Value) format. :param bytes signature: signature as bytes :rtype: bytes """ return DSASignature.from_p1363(signature).dump() def decode_ecdsa_signature(der): """ Decode a DER-encoded ASN.1 (ECDSA_Sig_Value) signature (as generated by OpenSSL/X.509) into PKCS #11 format. :param bytes der: DER-encoded signature :rtype bytes: """ asn1 = DSASignature.load(der) return asn1.to_p1363() python-pkcs11-0.7.0/pkcs11/exceptions.py0000664000372000037200000002050413717606207020650 0ustar travistravis00000000000000""" PKCS#11 return codes are exposed as Python exceptions inheriting from :class:`PKCS11Error`. """ class PKCS11Error(RuntimeError): """ Base exception for all PKCS#11 exceptions. """ class AlreadyInitialized(PKCS11Error): """ pkcs11 was already initialized with another library. """ class AnotherUserAlreadyLoggedIn(PKCS11Error): pass class AttributeTypeInvalid(PKCS11Error): pass class AttributeValueInvalid(PKCS11Error): pass class AttributeReadOnly(PKCS11Error): """ An attempt was made to set a value for an attribute which may not be set by the application, or which may not be modified by the application. """ class AttributeSensitive(PKCS11Error): """ An attempt was made to obtain the value of an attribute of an object which cannot be satisfied because the object is either sensitive or un-extractable. """ class ArgumentsBad(PKCS11Error): """ Bad arguments were passed into PKCS#11. This can indicate missing parameters to a mechanism or some other issue. Consult your PKCS#11 vendor documentation. """ class DataInvalid(PKCS11Error): """ The plaintext input data to a cryptographic operation is invalid. """ class DataLenRange(PKCS11Error): """ The plaintext input data to a cryptographic operation has a bad length. Depending on the operation’s mechanism, this could mean that the plaintext data is too short, too long, or is not a multiple of some particular block size. """ class DomainParamsInvalid(PKCS11Error): """ Invalid or unsupported domain parameters were supplied to the function. Which representation methods of domain parameters are supported by a given mechanism can vary from token to token. """ class DeviceError(PKCS11Error): pass class DeviceMemory(PKCS11Error): """ The token does not have sufficient memory to perform the requested function. """ class DeviceRemoved(PKCS11Error): """ The token was removed from its slot during the execution of the function. """ class EncryptedDataInvalid(PKCS11Error): """ The encrypted input to a decryption operation has been determined to be invalid ciphertext. """ class EncryptedDataLenRange(PKCS11Error): """ The ciphertext input to a decryption operation has been determined to be invalid ciphertext solely on the basis of its length. Depending on the operation’s mechanism, this could mean that the ciphertext is too short, too long, or is not a multiple of some particular block size. """ class ExceededMaxIterations(PKCS11Error): """ An iterative algorithm (for key pair generation, domain parameter generation etc.) failed because we have exceeded the maximum number of iterations. """ class FunctionCancelled(PKCS11Error): pass class FunctionFailed(PKCS11Error): pass class FunctionRejected(PKCS11Error): pass class FunctionNotSupported(PKCS11Error): pass class KeyHandleInvalid(PKCS11Error): pass class KeyIndigestible(PKCS11Error): pass class KeyNeeded(PKCS11Error): pass class KeyNotNeeded(PKCS11Error): pass class KeyNotWrappable(PKCS11Error): pass class KeySizeRange(PKCS11Error): pass class KeyTypeInconsistent(PKCS11Error): pass class KeyUnextractable(PKCS11Error): pass class GeneralError(PKCS11Error): """ In unusual (and extremely unpleasant!) circumstances, a function can fail with the return value CKR_GENERAL_ERROR. When this happens, the token and/or host computer may be in an inconsistent state, and the goals of the function may have been partially achieved. """ class HostMemory(PKCS11Error): """ The computer that the Cryptoki library is running on has insufficient memory to perform the requested function. """ class MechanismInvalid(PKCS11Error): """ Mechanism can not be used with requested operation. """ class MechanismParamInvalid(PKCS11Error): pass class MultipleObjectsReturned(PKCS11Error): """ Multiple objects matched the search parameters. """ class MultipleTokensReturned(PKCS11Error): """ Multiple tokens matched the search parameters. """ class NoSuchKey(PKCS11Error): """ No key matching the parameters was found. """ class NoSuchToken(PKCS11Error): """ No token matching the parameters was found. """ class ObjectHandleInvalid(PKCS11Error): pass class OperationActive(PKCS11Error): """ There is already an active operation (or combination of active operations) which prevents Cryptoki from activating the specified operation. For example, an active object-searching operation would prevent Cryptoki from activating an encryption operation with C_EncryptInit. Or, an active digesting operation and an active encryption operation would prevent Cryptoki from activating a signature operation. Or, on a token which doesn’t support simultaneous dual cryptographic operations in a session (see the description of the CKF_DUAL_CRYPTO_OPERATIONS flag in the CK_TOKEN_INFO structure), an active signature operation would prevent Cryptoki from activating an encryption operation. """ class OperationNotInitialized(PKCS11Error): pass class PinExpired(PKCS11Error): pass class PinIncorrect(PKCS11Error): pass class PinInvalid(PKCS11Error): pass class PinLenRange(PKCS11Error): """The specified PIN is too long or too short.""" class PinLocked(PKCS11Error): pass class PinTooWeak(PKCS11Error): pass class PublicKeyInvalid(PKCS11Error): pass class RandomNoRNG(PKCS11Error): pass class RandomSeedNotSupported(PKCS11Error): pass class SessionClosed(PKCS11Error): """ The session was closed during the execution of the function. """ class SessionCount(PKCS11Error): """ An attempt to open a session which does not succeed because there are too many existing sessions. """ class SessionExists(PKCS11Error): pass class SessionHandleInvalid(PKCS11Error): """ The session handle was invalid. This is usually caused by using an old session object that is not known to PKCS#11. """ class SessionReadOnly(PKCS11Error): """Attempted to write to a read-only session.""" class SessionReadOnlyExists(PKCS11Error): pass class SessionReadWriteSOExists(PKCS11Error): """ If the application calling :meth:`Token.open` already has a R/W SO session open with the token, then any attempt to open a R/O session with the token fails with this exception. """ class SignatureLenRange(PKCS11Error): pass class SignatureInvalid(PKCS11Error): pass class SlotIDInvalid(PKCS11Error): pass class TemplateIncomplete(PKCS11Error): """ Required attributes to create the object were missing. """ class TemplateInconsistent(PKCS11Error): """ Template values (including vendor defaults) are contradictory. """ class TokenNotPresent(PKCS11Error): """ The token was not present in its slot at the time that the function was invoked. """ class TokenNotRecognised(PKCS11Error): pass class TokenWriteProtected(PKCS11Error): pass class UnwrappingKeyHandleInvalid(PKCS11Error): pass class UnwrappingKeySizeRange(PKCS11Error): pass class UnwrappingKeyTypeInconsistent(PKCS11Error): pass class UserAlreadyLoggedIn(PKCS11Error): pass class UserNotLoggedIn(PKCS11Error): pass class UserPinNotInitialized(PKCS11Error): pass class UserTooManyTypes(PKCS11Error): """ An attempt was made to have more distinct users simultaneously logged into the token than the token and/or library permits. For example, if some application has an open SO session, and another application attempts to log the normal user into a session, the attempt may return this error. It is not required to, however. Only if the simultaneous distinct users cannot be supported does C_Login have to return this value. Note that this error code generalizes to true multi-user tokens. """ class WrappedKeyInvalid(PKCS11Error): pass class WrappedKeyLenRange(PKCS11Error): pass class WrappingKeyHandleInvalid(PKCS11Error): pass class WrappingKeySizeRange(PKCS11Error): pass class WrappingKeyTypeInconsistent(PKCS11Error): pass python-pkcs11-0.7.0/pkcs11/_mswin.pxd0000664000372000037200000000721313717606207020130 0ustar travistravis00000000000000#!python #cython: language_level=3 # # MIT License # # Copyright 2019 Eric Devolder # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Definitions to support compilation on Windows platform """ cdef extern from "Windows.h": ctypedef unsigned long DWORD ctypedef Py_UNICODE wchar_t ctypedef wchar_t *LPWSTR ctypedef const wchar_t *LPCWSTR ctypedef char *LPSTR ctypedef const char *LPCSTR ctypedef void *PVOID ctypedef const void *LPCVOID ctypedef PVOID HANDLE ctypedef HANDLE HLOCAL ctypedef HANDLE HINSTANCE ctypedef HINSTANCE HMODULE ctypedef bint BOOL ctypedef short INT16 ctypedef enum LANG_ID: LANG_NEUTRAL LANG_USER_DEFAULT SUBLANG_DEFAULT ctypedef enum FORMAT_FLAGS: FORMAT_MESSAGE_ALLOCATE_BUFFER FORMAT_MESSAGE_FROM_SYSTEM FORMAT_MESSAGE_IGNORE_INSERTS HMODULE LoadLibraryW(LPCWSTR lpLibFileName) BOOL FreeLibrary(HMODULE hLinModule) PVOID GetProcAddress(HMODULE hModule, LPCSTR lpProcName) DWORD GetLastError() DWORD MAKELANGID(INT16 p, INT16 s) DWORD FormatMessageW( DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPWSTR lpBuffer, DWORD nSize, ... ) HLOCAL LocalFree(HLOCAL handle) cdef inline winerror(so) with gil: """ returns the last error message, as a string. If the string has '%1', it is substituted with the content of 'so' arg. """ # # inspired from https://docs.microsoft.com/en-us/windows/desktop/debug/retrieving-the-last-error-code # cdef LPWSTR msgbuffer = NULL dw = GetLastError() errmsg = "" if dw != 0: # from https://docs.microsoft.com/en-us/windows/desktop/api/WinBase/nf-winbase-formatmessage # at 'Security Remarks': # In particular, it is unsafe to take an arbitrary system error code returned from an API # and use FORMAT_MESSAGE_FROM_SYSTEM without FORMAT_MESSAGE_IGNORE_INSERTS. # # Given that remark, we are not attempting to parse inserts with a va_list. # Instead, we only substitute '%1' with the value of so argument, on the returned string. FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_USER_DEFAULT, SUBLANG_DEFAULT), &msgbuffer, 0, NULL) errmsg = msgbuffer # C to python string copy LocalFree(msgbuffer) return errmsg.replace('%1', so) #EOF python-pkcs11-0.7.0/pkcs11/types.py0000664000372000037200000011102113717606207017626 0ustar travistravis00000000000000""" Types for high level PKCS#11 wrapper. This module provides stubs that are overrideen in pkcs11._pkcs11. """ from threading import RLock from binascii import hexlify from cached_property import cached_property from .constants import ( Attribute, MechanismFlag, ObjectClass, SlotFlag, TokenFlag, UserType, ) from .mechanisms import KeyType, Mechanism from .exceptions import ( ArgumentsBad, AttributeTypeInvalid, NoSuchKey, MultipleObjectsReturned, SignatureInvalid, SignatureLenRange, ) PROTECTED_AUTH = object() """Indicate the pin should be supplied via an external mechanism (e.g. pin pad)""" def _CK_UTF8CHAR_to_str(data): """Convert CK_UTF8CHAR to string.""" return data.decode('utf-8').rstrip() def _CK_VERSION_to_tuple(data): """Convert CK_VERSION to tuple.""" return (data['major'], data['minor']) def _CK_MECHANISM_TYPE_to_enum(mechanism): """Convert CK_MECHANISM_TYPE to enum or be okay.""" try: return Mechanism(mechanism) except ValueError: return mechanism class MechanismInfo: """ Information about a mechanism. See :meth:`pkcs11.Slot.get_mechanism_info`. """ def __init__(self, slot, mechanism, ulMinKeySize=None, ulMaxKeySize=None, flags=None, **kwargs): self.slot = slot """:class:`pkcs11.Slot` this information is for.""" self.mechanism = mechanism """:class:`pkcs11.mechanisms.Mechanism` this information is for.""" self.min_key_length = ulMinKeySize """Minimum key length in bits (:class:`int`).""" self.max_key_length = ulMaxKeySize """Maximum key length in bits (:class:`int`).""" self.flags = MechanismFlag(flags) """Mechanism capabilities (:class:`pkcs11.constants.MechanismFlag`).""" def __str__(self): return '\n'.join(( "Supported key lengths: [%s, %s]" % (self.min_key_length, self.max_key_length), "Flags: %s" % self.flags, )) def __repr__(self): return '<{klass} (mechanism={mechanism}, flags={flags})>'.format( klass=type(self).__name__, mechanism=str(self.mechanism), flags=str(self.flags)) class Slot: """ A PKCS#11 device slot. This object represents a physical or software slot exposed by PKCS#11. A slot has hardware capabilities, e.g. supported mechanisms and may has a physical or software :class:`Token` installed. """ def __init__(self, lib, slot_id, slotDescription=None, manufacturerID=None, hardwareVersion=None, firmwareVersion=None, flags=None, **kwargs): self._lib = lib # Hold a reference to the lib to prevent gc self.slot_id = slot_id """Slot identifier (opaque).""" self.slot_description = _CK_UTF8CHAR_to_str(slotDescription) """Slot name (:class:`str`).""" self.manufacturer_id = _CK_UTF8CHAR_to_str(manufacturerID) """Slot/device manufacturer's name (:class:`str`).""" self.hardware_version = _CK_VERSION_to_tuple(hardwareVersion) """Hardware version (:class:`tuple`).""" self.firmware_version = _CK_VERSION_to_tuple(firmwareVersion) """Firmware version (:class:`tuple`).""" self.flags = SlotFlag(flags) """Capabilities of this slot (:class:`SlotFlag`).""" def get_token(self): """ Returns the token loaded into this slot. :rtype: Token """ raise NotImplementedError() def get_mechanisms(self): """ Returns the mechanisms supported by this device. :rtype: set(Mechanism) """ raise NotImplementedError() def get_mechanism_info(self, mechanism): """ Returns information about the mechanism. :param Mechanism mechanism: mechanism to learn about :rtype: MechanismInfo """ raise NotImplementedError() def __eq__(self, other): return self.slot_id == other.slot_id def __str__(self): return '\n'.join(( "Slot Description: %s" % self.slot_description, "Manufacturer ID: %s" % self.manufacturer_id, "Hardware Version: %s.%s" % self.hardware_version, "Firmware Version: %s.%s" % self.firmware_version, "Flags: %s" % self.flags, )) def __repr__(self): return '<{klass} (slotID={slot_id} flags={flags})>'.format( klass=type(self).__name__, slot_id=self.slot_id, flags=str(self.flags)) class Token: """ A PKCS#11 token. A token can be physically installed in a :class:`Slot`, or a software token, depending on your PKCS#11 library. """ def __init__(self, slot, label=None, serialNumber=None, model=None, manufacturerID=None, hardwareVersion=None, firmwareVersion=None, flags=None, **kwargs): self.slot = slot """The :class:`Slot` this token is installed in.""" self.label = _CK_UTF8CHAR_to_str(label) """Label of this token (:class:`str`).""" self.serial = serialNumber.rstrip() """Serial number of this token (:class:`bytes`).""" self.manufacturer_id = _CK_UTF8CHAR_to_str(manufacturerID) """Manufacturer ID.""" self.model = _CK_UTF8CHAR_to_str(model) """Model name.""" self.hardware_version = _CK_VERSION_to_tuple(hardwareVersion) """Hardware version (:class:`tuple`).""" self.firmware_version = _CK_VERSION_to_tuple(firmwareVersion) """Firmware version (:class:`tuple`).""" self.flags = TokenFlag(flags) """Capabilities of this token (:class:`pkcs11.flags.TokenFlag`).""" def __eq__(self, other): return self.slot == other.slot def open(self, rw=False, user_pin=None, so_pin=None): """ Open a session on the token and optionally log in as a user or security officer (pass one of `user_pin` or `so_pin`). Pass PROTECTED_AUTH to indicate the pin should be supplied via an external mechanism (e.g. pin pad). Can be used as a context manager or close with :meth:`Session.close`. :: with token.open() as session: print(session) :param rw: True to create a read/write session. :param bytes user_pin: Authenticate to this session as a user. :param bytes so_pin: Authenticate to this session as a security officer. :rtype: Session """ raise NotImplementedError() def __str__(self): return self.label def __repr__(self): return "<{klass} (label='{label}' serial={serial} flags={flags})>"\ .format(klass=type(self).__name__, label=self.label, serial=self.serial, flags=str(self.flags)) class Session: """ A PKCS#11 :class:`Token` session. A session is required to do nearly all operations on a token including encryption/signing/keygen etc. Create a session using :meth:`Token.open`. Sessions can be used as a context manager or closed with :meth:`close`. """ def __init__(self, token, handle, rw=False, user_type=UserType.NOBODY): self.token = token """:class:`Token` this session is on.""" self._handle = handle # Big operation lock prevents other threads from entering/reentering # operations. If the same thread enters the lock, they will get a # Cryptoki warning self._operation_lock = RLock() self.rw = rw """True if this is a read/write session.""" self.user_type = user_type """User type for this session (:class:`pkcs11.constants.UserType`).""" def __eq__(self, other): return self.token == other.token and \ self._handle == other._handle def __hash__(self): return hash(self._handle) def __enter__(self): return self def __exit__(self, type_, value, traceback): self.close() def close(self): """Close the session.""" raise NotImplementedError() def get_key(self, object_class=None, key_type=None, label=None, id=None): """ Search for a key with any of `key_type`, `label` and/or `id`. Returns a single key or throws :class:`pkcs11.exceptions.NoSuchKey` or :class:`pkcs11.exceptions.MultipleObjectsReturned`. This is a simplified version of :meth:`get_objects`, which allows searching for any object. :param ObjectClass object_class: Optional object class. :param KeyType key_type: Optional key type. :param str label: Optional key label. :param bytes id: Optional key id. :rtype: Key """ if object_class is None and \ key_type is None and \ label is None \ and id is None: raise ArgumentsBad("Must specify at least one search parameter.") attrs = {} if object_class is not None: attrs[Attribute.CLASS] = object_class if key_type is not None: attrs[Attribute.KEY_TYPE] = key_type if label is not None: attrs[Attribute.LABEL] = label if id is not None: attrs[Attribute.ID] = id iterator = self.get_objects(attrs) try: try: key = next(iterator) except StopIteration: raise NoSuchKey("No key matching %s" % attrs) try: next(iterator) raise MultipleObjectsReturned("More than 1 key matches %s" % attrs) except StopIteration: return key finally: # Force finalizing SearchIter rather than waiting for garbage # collection, so that we release the operation lock. iterator._finalize() def get_objects(self, attrs=None): """ Search for objects matching `attrs`. Returns a generator. :: for obj in session.get_objects({ Attribute.CLASS: ObjectClass.SECRET_KEY, Attribute.LABEL: 'MY LABEL', }): print(obj) This is the more generic version of :meth:`get_key`. :param dict(Attribute,*) attrs: Attributes to search for. :rtype: iter(Object) """ raise NotImplementedError() def create_object(self, attrs): """ Create a new object on the :class:`Token`. This is a low-level interface to create any type of object and can be used for importing data onto the Token. :: key = session.create_object({ pkcs11.Attribute.CLASS: pkcs11.ObjectClass.SECRET_KEY, pkcs11.Attribute.KEY_TYPE: pkcs11.KeyType.AES, pkcs11.Attribute.VALUE: b'SUPER SECRET KEY', }) For generating keys see :meth:`generate_key` or :meth:`generate_keypair`. For importing keys see :ref:`importing-keys`. Requires a read/write session, unless the object is not to be stored. :param dict(Attribute,*) attrs: attributes of the object to create :rtype: Object """ raise NotImplementedError() def create_domain_parameters(self, key_type, attrs, local=False, store=False): """ Create a domain parameters object from known parameters. Domain parameters are used for key generation of key types such as DH, DSA and EC. You can also generate new parameters using :meth:`generate_domain_parameters`. The `local` parameter creates a Python object that is not created on the HSM (its object handle will be unset). This is useful if you only need the domain parameters to create another object, and do not need a real PKCS #11 object in the session. .. warning:: Domain parameters have no id or labels. Storing them is possible but be aware they may be difficult to retrieve. :param KeyType key_type: Key type these parameters are for :param dict(Attribute,*) attrs: Domain parameters (specific tp `key_type`) :param local: if True, do not transfer parameters to the HSM. :param store: if True, store these parameters permanently in the HSM. :rtype: DomainParameters """ raise NotImplementedError() def generate_domain_parameters(self, key_type, param_length, store=False, mechanism=None, mechanism_param=None, template=None): """ Generate domain parameters. See :meth:`create_domain_parameters` for creating domain parameter objects from known parameters. See :meth:`generate_key` for documentation on mechanisms and templates. .. warning:: Domain parameters have no id or labels. Storing them is possible but be aware they may be difficult to retrieve. :param KeyType key_type: Key type these parameters are for :param int params_length: Size of the parameters (e.g. prime length) in bits. :param store: Store these parameters in the HSM :param Mechanism mechanism: Optional generation mechanism (or default) :param bytes mechanism_param: Optional mechanism parameter. :param dict(Attribute,*) template: Optional additional attributes. :rtype: DomainParameters """ raise NotImplementedError() def generate_key(self, key_type, key_length=None, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, template=None): """ Generate a single key (e.g. AES, DES). Keys should set at least `id` or `label`. An appropriate `mechanism` will be chosen for `key_type` (see :attr:`DEFAULT_GENERATE_MECHANISMS`) or this can be overridden. Similarly for the `capabilities` (see :attr:`DEFAULT_KEY_CAPABILITIES`). The `template` will extend the default template used to make the key. Possible mechanisms and template attributes are defined by `PKCS #11 `_. Invalid mechanisms or attributes should raise :exc:`pkcs11.exceptions.MechanismInvalid` and :exc:`pkcs11.exceptions.AttributeTypeInvalid` respectively. :param KeyType key_type: Key type (e.g. KeyType.AES) :param int key_length: Key length in bits (e.g. 256). :param bytes id: Key identifier. :param str label: Key label. :param store: Store key on token (requires R/W session). :param MechanismFlag capabilities: Key capabilities (or default). :param Mechanism mechanism: Generation mechanism (or default). :param bytes mechanism_param: Optional vector to the mechanism. :param dict(Attribute,*) template: Additional attributes. :rtype: SecretKey """ raise NotImplementedError() def generate_keypair(self, key_type, key_length=None, **kwargs): """ Generate a asymmetric keypair (e.g. RSA). See :meth:`generate_key` for more information. :param KeyType key_type: Key type (e.g. KeyType.DSA) :param int key_length: Key length in bits (e.g. 256). :param bytes id: Key identifier. :param str label: Key label. :param store: Store key on token (requires R/W session). :param MechanismFlag capabilities: Key capabilities (or default). :param Mechanism mechanism: Generation mechanism (or default). :param bytes mechanism_param: Optional vector to the mechanism. :param dict(Attribute,*) template: Additional attributes. :rtype: (PublicKey, PrivateKey) """ if key_type is KeyType.DSA: if key_length is None: raise ArgumentsBad("Must specify `key_length`") params = self.generate_domain_parameters(key_type, key_length) return params.generate_keypair(**kwargs) else: return self._generate_keypair(key_type, key_length=key_length, **kwargs) def seed_random(self, seed): """ Mix additional seed material into the RNG (if supported). :param bytes seed: Bytes of random to seed. """ raise NotImplementedError() def generate_random(self, nbits): """ Generate `length` bits of random or pseudo-random data (if supported). :param int nbits: Number of bits to generate. :rtype: bytes """ raise NotImplementedError() def digest(self, data, **kwargs): """ Digest `data` using `mechanism`. `data` can be a single value or an iterator. :class:`Key` objects can also be digested, optionally interspersed with :class:`bytes`. :param data: Data to digest :type data: str, bytes, Key or iter(bytes, Key) :param Mechanism mechanism: digest mechanism :param bytes mechanism_param: optional mechanism parameter :rtype: bytes """ # If data is a string, encode it now as UTF-8. if isinstance(data, str): data = data.encode('utf-8') if isinstance(data, bytes): return self._digest(data, **kwargs) elif isinstance(data, Key): data = (data,) return self._digest_generator(data, **kwargs) class Object: """ A PKCS#11 object residing on a :class:`Token`. Objects implement :meth:`__getitem__` and :meth:`__setitem__` to retrieve :class:`pkcs11.constants.Attribute` values on the object. Valid attributes for an object are given in `PKCS #11 `_. Invalid attributes should raise :exc:`pkcs11.exceptions.AttributeTypeInvalid`. """ object_class = None """:class:`pkcs11.constants.ObjectClass` of this Object.""" def __init__(self, session, handle): self.session = session """:class:`Session` this object is valid for.""" self._handle = handle def __eq__(self, other): return self.session == other.session and \ self._handle == other._handle def __hash__(self): return hash((self.session, self._handle)) def copy(self, attrs): """ Make a copy of the object with new attributes `attrs`. Requires a read/write session, unless the object is not to be stored. :: new = key.copy({ Attribute.LABEL: 'MY NEW KEY', }) Certain objects may not be copied. Calling :meth:`copy` on such objects will result in an exception. :param dict(Attribute,*) attrs: attributes for the new :class:`Object` :rtype: Object """ raise NotImplementedError() def destroy(self): """ Destroy the object. Requires a read/write session, unless the object is not stored. Certain objects may not be destroyed. Calling :meth:`destroy` on such objects will result in an exception. The :class:`Object` is no longer valid. """ raise NotImplementedError() class DomainParameters(Object): """ PKCS#11 Domain Parameters. Used to store domain parameters as part of the key generation step, e.g. in DSA and Diffie-Hellman. """ def __init__(self, session, handle, params=None): super().__init__(session, handle) self.params = params def __getitem__(self, key): if self._handle is None: try: return self.params[key] except KeyError: raise AttributeTypeInvalid else: return super().__getitem__(key) def __setitem__(self, key, value): if self._handle is None: self.params[key] = value else: super().__setitem__(key, value) @cached_property def key_type(self): """ Key type (:class:`pkcs11.mechanisms.KeyType`) these parameters can be used to generate. """ return self[Attribute.KEY_TYPE] def generate_keypair(self, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, public_template=None, private_template=None): """ Generate a key pair from these domain parameters (e.g. for Diffie-Hellman. See :meth:`Session.generate_key` for more information. :param bytes id: Key identifier. :param str label: Key label. :param store: Store key on token (requires R/W session). :param MechanismFlag capabilities: Key capabilities (or default). :param Mechanism mechanism: Generation mechanism (or default). :param bytes mechanism_param: Optional vector to the mechanism. :param dict(Attribute,*) template: Additional attributes. :rtype: (PublicKey, PrivateKey) """ raise NotImplementedError() class Key(Object): """Base class for all key :class:`Object` types.""" @cached_property def id(self): """Key id (:class:`bytes`).""" return self[Attribute.ID] @cached_property def label(self): """Key label (:class:`str`).""" return self[Attribute.LABEL] @cached_property def key_type(self): """Key type (:class:`pkcs11.mechanisms.KeyType`).""" return self[Attribute.KEY_TYPE] @cached_property def _key_description(self): """A description of the key.""" try: return '%s-bit %s' % (self.key_length, self.key_type.name) except AttributeTypeInvalid: return self.key_type.name def __repr__(self): return "<%s label='%s' id='%s' %s>" % ( type(self).__name__, self.label, hexlify(self.id).decode('ascii'), self._key_description) class SecretKey(Key): """ A PKCS#11 :attr:`pkcs11.constants.ObjectClass.SECRET_KEY` object (symmetric encryption key). """ object_class = ObjectClass.SECRET_KEY @cached_property def key_length(self): """Key length in bits.""" return self[Attribute.VALUE_LEN] * 8 class PublicKey(Key): """ A PKCS#11 :attr:`pkcs11.constants.ObjectClass.PUBLIC_KEY` object (asymmetric public key). RSA private keys can be imported and exported from PKCS#1 DER-encoding using :func:`pkcs11.util.rsa.decode_rsa_public_key` and :func:`pkcs11.util.rsa.encode_rsa_public_key` respectively. """ object_class = ObjectClass.PUBLIC_KEY @cached_property def key_length(self): """Key length in bits.""" return self[Attribute.MODULUS_BITS] class PrivateKey(Key): """ A PKCS#11 :attr:`pkcs11.constants.ObjectClass.PRIVATE_KEY` object (asymmetric private key). RSA private keys can be imported from PKCS#1 DER-encoding using :func:`pkcs11.util.rsa.decode_rsa_private_key`. .. warning:: Private keys imported directly, rather than unwrapped from a trusted private key should be considered insecure. """ object_class = ObjectClass.PRIVATE_KEY @cached_property def key_length(self): """Key length in bits.""" return len(self[Attribute.MODULUS]) * 8 class Certificate(Object): """ A PKCS#11 :attr:`pkcs11.constants.ObjectClass.CERTIFICATE` object. PKCS#11 is limited in its handling of certificates, and does not provide features like parsing of X.509 etc. These should be handled in an external library. PKCS#11 will not set attributes on the certificate based on the `VALUE`. :func:`pkcs11.util.x509.decode_x509_certificate` will extract attributes from a certificate to create the object. """ object_class = ObjectClass.CERTIFICATE @cached_property def certificate_type(self): """ The type of certificate. :rtype: CertificateType """ return self[Attribute.CERTIFICATE_TYPE] class EncryptMixin(Object): """ This :class:`Object` supports the encrypt capability. """ def encrypt(self, data, buffer_size=8192, **kwargs): """ Encrypt some `data`. Data can be either :class:`str` or :class:`bytes`, in which case it will return :class:`bytes`; or an iterable of :class:`bytes` in which case it will return a generator yielding :class:`bytes` (be aware, more chunks will be output than input). If you do not specify `mechanism` then the default from :attr:`DEFAULT_ENCRYPT_MECHANISMS` will be used. If an iterable is passed and the mechanism chosen does not support handling data in chunks, an exception will be raised. Some mechanisms (including the default CBC mechanisms) require additional parameters, e.g. an initialisation vector [#]_, to the mechanism. Pass this as `mechanism_param`. Documentation of these parameters is given specified in `PKCS #11 `_. When passing an iterable for data `buffer_size` must be sufficient to store the working buffer. An integer number of blocks and greater than or equal to the largest input chunk is recommended. The returned generator obtains a lock on the :class:`Session` to prevent other threads from starting a simultaneous operation. The lock is released when you consume/destroy the generator. See :ref:`concurrency`. .. warning:: It's not currently possible to cancel an encryption operation by deleting the generator. You must consume the generator to complete the operation. An example of streaming a file is as follows: :: def encrypt_file(file_in, file_out, buffer_size=8192): with \\ open(file_in, 'rb') as input_, \\ open(file_out, 'wb') as output: chunks = iter(lambda: input_.read(buffer_size), '') for chunk in key.encrypt(chunks, mechanism_param=iv, buffer_size=buffer_size): output.write(chunk) :param data: data to encrypt :type data: str, bytes or iter(bytes) :param Mechanism mechanism: optional encryption mechanism (or None for default) :param bytes mechanism_param: optional mechanism parameter (e.g. initialisation vector). :param int buffer_size: size of the working buffer (for generators) :rtype: bytes or iter(bytes) .. [#] The initialisation vector should contain quality random, e.g. from :meth:`Session.generate_random`. This method will not return the value of the initialisation vector as part of the encryption. You must store that yourself. """ # If data is a string, encode it now as UTF-8. if isinstance(data, str): data = data.encode('utf-8') if isinstance(data, bytes): return self._encrypt(data, **kwargs) else: return self._encrypt_generator(data, buffer_size=buffer_size, **kwargs) class DecryptMixin(Object): """ This :class:`Object` supports the decrypt capability. """ def decrypt(self, data, buffer_size=8192, **kwargs): """ Decrypt some `data`. See :meth:`EncryptMixin.encrypt` for more information. :param data: data to decrypt :type data: bytes or iter(bytes) :param Mechanism mechanism: optional encryption mechanism (or None for default). :param bytes mechanism_param: optional mechanism parameter (e.g. initialisation vector). :param int buffer_size: size of the working buffer (for generators). :rtype: bytes or iter(bytes) """ # If we're not an iterable, call into our generator with an iterable # version and join the result at the end. if isinstance(data, bytes): return self._decrypt(data, **kwargs) else: return self._decrypt_generator(data, buffer_size=buffer_size, **kwargs) class SignMixin(Object): """ This :class:`Object` supports the sign capability. """ def sign(self, data, **kwargs): """ Sign some `data`. See :meth:`EncryptMixin.encrypt` for more information. For DSA and ECDSA keys, PKCS #11 outputs the two parameters (r & s) as two concatenated `biginteger` of the same length. To convert these into other formats, such as the format used by OpenSSL, use :func:`pkcs11.util.dsa.encode_dsa_signature` or :func:`pkcs11.util.ec.encode_ecdsa_signature`. :param data: data to sign :type data: str, bytes or iter(bytes) :param Mechanism mechanism: optional signing mechanism :param bytes mechanism_param: optional mechanism parameter :rtype: bytes """ # If data is a string, encode it now as UTF-8. if isinstance(data, str): data = data.encode('utf-8') if isinstance(data, bytes): return self._sign(data, **kwargs) else: return self._sign_generator(data, **kwargs) class VerifyMixin(Object): """ This :class:`Object` supports the verify capability. """ def verify(self, data, signature, **kwargs): """ Verify some `data`. See :meth:`EncryptMixin.encrypt` for more information. Returns True if `signature` is valid for `data`. For DSA and ECDSA keys, PKCS #11 expects the two parameters (r & s) as two concatenated `biginteger` of the same length. To convert these from other formats, such as the format used by OpenSSL, use :func:`pkcs11.util.dsa.decode_dsa_signature` or :func:`pkcs11.util.ec.decode_ecdsa_signature`. :param data: data to sign :type data: str, bytes or iter(bytes) :param bytes signature: signature :param Mechanism mechanism: optional signing mechanism :param bytes mechanism_param: optional mechanism parameter :rtype: bool """ # If data is a string, encode it now as UTF-8. if isinstance(data, str): data = data.encode('utf-8') try: if isinstance(data, bytes): self._verify(data, signature, **kwargs) else: self._verify_generator(data, signature, **kwargs) return True except (SignatureInvalid, SignatureLenRange): return False class WrapMixin(Object): """ This :class:`Object` supports the wrap capability. """ def wrap_key(self, key, mechanism=None, mechanism_param=None): """ Use this key to wrap (i.e. encrypt) `key` for export. Returns an encrypted version of `key`. `key` must have :attr:`Attribute.EXTRACTABLE` = True. :param Key key: key to export :param Mechanism mechanism: wrapping mechanism (or None for default). :param bytes mechanism_param: mechanism parameter (if required) :rtype: bytes """ raise NotImplementedError() class UnwrapMixin(Object): """ This :class:`Object` supports the unwrap capability. """ def unwrap_key(self, object_class, key_type, key_data, id=None, label=None, mechanism=None, mechanism_param=None, store=False, capabilities=None, template=None): """ Use this key to unwrap (i.e. decrypt) and import `key_data`. See :class:`Session.generate_key` for more information. :param ObjectClass object_class: Object class to import as :param KeyType key_type: Key type (e.g. KeyType.AES) :param bytes key_data: Encrypted key to unwrap :param bytes id: Key identifier. :param str label: Key label. :param store: Store key on token (requires R/W session). :param MechanismFlag capabilities: Key capabilities (or default). :param Mechanism mechanism: Generation mechanism (or default). :param bytes mechanism_param: Optional vector to the mechanism. :param dict(Attribute,*) template: Additional attributes. :rtype: Key """ raise NotImplementedError() class DeriveMixin(Object): """ This :class:`Object` supports the derive capability. """ def derive_key(self, key_type, key_length, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, template=None): """ Derive a new key from this key. Used to create session keys from a PKCS key exchange. Typically the mechanism, e.g. Diffie-Hellman, requires you to specify the other party's piece of shared information as the `mechanism_param`. Some mechanisms require a tuple of data (see :class:`pkcs11.mechanisms.Mechanism`). See :class:`Session.generate_key` for more documentation on key generation. Diffie-Hellman example: :: # Diffie-Hellman domain parameters # e.g. from RFC 3526, RFC 5114 or `openssl dhparam` prime = [0xFF, ...] base = [0x02] parameters = session.create_domain_parameters(KeyType.DH, { Attribute.PRIME: prime, Attribute.BASE: base, }, local=True) # Alice generates a DH key pair from the public # Diffie-Hellman parameters public, private = parameters.generate_keypair() alices_value = public[Attribute.VALUE] # Bob generates a DH key pair from the same parameters. # Alice exchanges public values with Bob... # She sends `alices_value` and receives `bobs_value`. # (Assuming Alice is doing AES CBC, she also needs to send an IV) # Alice generates a session key with Bob's public value # Bob will generate the same session key using Alice's value. session_key = private.derive_key( KeyType.AES, 128, mechanism_param=bobs_value) Elliptic-Curve Diffie-Hellman example: :: # DER encoded EC params, e.g. from OpenSSL # openssl ecparam -outform der -name prime192v1 | base64 # # Check what EC parameters the module supports with # slot.get_module_info() parameters = session.create_domain_parameters(KeyType.EC, { Attribute.EC_PARAMS: b'...', }, local=True) # Alice generates a EC key pair, and gets her public value public, private = parameters.generate_keypair() alices_value = public[Attribute.EC_POINT] # Bob generates a DH key pair from the same parameters. # Alice exchanges public values with Bob... # She sends `alices_value` and receives `bobs_value`. # Alice generates a session key with Bob's public value # Bob will generate the same session key using Alice's value. session_key = private.derive_key( KeyType.AES, 128, mechanism_param=(KDF.NULL, None, bobs_value)) :param KeyType key_type: Key type (e.g. KeyType.AES) :param int key_length: Key length in bits (e.g. 256). :param bytes id: Key identifier. :param str label: Key label. :param store: Store key on token (requires R/W session). :param MechanismFlag capabilities: Key capabilities (or default). :param Mechanism mechanism: Generation mechanism (or default). :param bytes mechanism_param: Optional vector to the mechanism. :param dict(Attribute,*) template: Additional attributes. :rtype: SecretKey """ raise NotImplementedError() python-pkcs11-0.7.0/pkcs11/__init__.py0000664000372000037200000000123713717606207020230 0ustar travistravis00000000000000""" :mod:`pkcs11` defines a high-level, "Pythonic" interface to PKCS#11. """ from .constants import * # noqa: F403 from .exceptions import * # noqa: F403 from .mechanisms import * # noqa: F403 from .types import * # noqa: F403 _so = None _lib = None def lib(so): """ Wrap the main library call coming from Cython with a preemptive dynamic loading. """ global _lib global _so if _lib: if _so != so: raise AlreadyInitialized( # noqa: F405 "Already initialized with %s" % so) else: return _lib from . import _pkcs11 _lib = _pkcs11.lib(so) _so = so return _lib python-pkcs11-0.7.0/pkcs11/_errors.pyx0000664000372000037200000001005213717606207020327 0ustar travistravis00000000000000""" Map from CKR return codes to Python exceptions. """ from .exceptions import * cdef ERROR_MAP = { CKR_ATTRIBUTE_TYPE_INVALID: AttributeTypeInvalid, CKR_ATTRIBUTE_VALUE_INVALID: AttributeValueInvalid, CKR_ATTRIBUTE_READ_ONLY: AttributeReadOnly, CKR_ATTRIBUTE_SENSITIVE: AttributeSensitive, CKR_ARGUMENTS_BAD: ArgumentsBad, CKR_BUFFER_TOO_SMALL: MemoryError("Buffer was too small. Should never see this."), CKR_CRYPTOKI_ALREADY_INITIALIZED: RuntimeError("Initialisation error (already initialized). Should never see this."), CKR_CRYPTOKI_NOT_INITIALIZED: RuntimeError("Initialisation error (not initialized). Should never see this."), CKR_DATA_INVALID: DataInvalid, CKR_DATA_LEN_RANGE: DataLenRange, CKR_DOMAIN_PARAMS_INVALID: DomainParamsInvalid, CKR_DEVICE_ERROR: DeviceError, CKR_DEVICE_MEMORY: DeviceMemory, CKR_DEVICE_REMOVED: DeviceRemoved, CKR_ENCRYPTED_DATA_INVALID: EncryptedDataInvalid, CKR_ENCRYPTED_DATA_LEN_RANGE: EncryptedDataLenRange, CKR_EXCEEDED_MAX_ITERATIONS: ExceededMaxIterations, CKR_FUNCTION_CANCELED: FunctionCancelled, CKR_FUNCTION_FAILED: FunctionFailed, CKR_FUNCTION_REJECTED: FunctionRejected, CKR_FUNCTION_NOT_SUPPORTED: FunctionNotSupported, CKR_KEY_HANDLE_INVALID: KeyHandleInvalid, CKR_KEY_INDIGESTIBLE: KeyIndigestible, CKR_KEY_NEEDED: KeyNeeded, CKR_KEY_NOT_NEEDED: KeyNotNeeded, CKR_KEY_SIZE_RANGE: KeySizeRange, CKR_KEY_NOT_WRAPPABLE: KeyNotWrappable, CKR_KEY_TYPE_INCONSISTENT: KeyTypeInconsistent, CKR_KEY_UNEXTRACTABLE: KeyUnextractable, CKR_GENERAL_ERROR: GeneralError, CKR_HOST_MEMORY: HostMemory, CKR_MECHANISM_INVALID: MechanismInvalid, CKR_MECHANISM_PARAM_INVALID: MechanismParamInvalid, CKR_OBJECT_HANDLE_INVALID: ObjectHandleInvalid, CKR_OPERATION_ACTIVE: OperationActive, CKR_OPERATION_NOT_INITIALIZED: OperationNotInitialized, CKR_PIN_EXPIRED: PinExpired, CKR_PIN_INCORRECT: PinIncorrect, CKR_PIN_INVALID: PinInvalid, CKR_PIN_LOCKED: PinLocked, CKR_PIN_TOO_WEAK: PinTooWeak, CKR_PUBLIC_KEY_INVALID: PublicKeyInvalid, CKR_RANDOM_NO_RNG: RandomNoRNG, CKR_RANDOM_SEED_NOT_SUPPORTED: RandomSeedNotSupported, CKR_SESSION_CLOSED: SessionClosed, CKR_SESSION_COUNT: SessionCount, CKR_SESSION_EXISTS: SessionExists, CKR_SESSION_HANDLE_INVALID: SessionHandleInvalid, CKR_SESSION_PARALLEL_NOT_SUPPORTED: RuntimeError("Parallel not supported. Should never see this."), CKR_SESSION_READ_ONLY: SessionReadOnly, CKR_SESSION_READ_ONLY_EXISTS: SessionReadOnlyExists, CKR_SESSION_READ_WRITE_SO_EXISTS: SessionReadWriteSOExists, CKR_SIGNATURE_LEN_RANGE: SignatureLenRange, CKR_SIGNATURE_INVALID: SignatureInvalid, CKR_TEMPLATE_INCOMPLETE: TemplateIncomplete, CKR_TEMPLATE_INCONSISTENT: TemplateInconsistent, CKR_SLOT_ID_INVALID: SlotIDInvalid, CKR_TOKEN_NOT_PRESENT: TokenNotPresent, CKR_TOKEN_NOT_RECOGNIZED: TokenNotRecognised, CKR_TOKEN_WRITE_PROTECTED: TokenWriteProtected, CKR_UNWRAPPING_KEY_HANDLE_INVALID: UnwrappingKeyHandleInvalid, CKR_UNWRAPPING_KEY_SIZE_RANGE: UnwrappingKeySizeRange, CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: UnwrappingKeyTypeInconsistent, CKR_USER_NOT_LOGGED_IN: UserNotLoggedIn, CKR_USER_ALREADY_LOGGED_IN: UserAlreadyLoggedIn, CKR_USER_ANOTHER_ALREADY_LOGGED_IN: AnotherUserAlreadyLoggedIn, CKR_USER_PIN_NOT_INITIALIZED: UserPinNotInitialized, CKR_USER_TOO_MANY_TYPES: UserTooManyTypes, CKR_USER_TYPE_INVALID: RuntimeError("User type invalid. Should never see this."), CKR_WRAPPED_KEY_INVALID: WrappedKeyInvalid, CKR_WRAPPED_KEY_LEN_RANGE: WrappedKeyLenRange, CKR_WRAPPING_KEY_HANDLE_INVALID: WrappingKeyHandleInvalid, CKR_WRAPPING_KEY_SIZE_RANGE: WrappingKeySizeRange, CKR_WRAPPING_KEY_TYPE_INCONSISTENT: WrappingKeyTypeInconsistent, } cpdef void assertRV(CK_RV rv) nogil except *: """Check for an acceptable RV value or thrown an exception.""" if rv != CKR_OK: raise ERROR_MAP.get(rv, PKCS11Error("Unmapped error code %s" % hex(rv))) python-pkcs11-0.7.0/pkcs11/_pkcs11.pyx0000664000372000037200000015270413717606207020130 0ustar travistravis00000000000000#!python #cython: language_level=3 """ High-level Python PKCS#11 Wrapper. Most class here inherit from pkcs11.types, which provides easier introspection for Sphinx/Jedi/etc, as this module is not importable without having the library loaded. """ from __future__ import (absolute_import, unicode_literals, print_function, division) from cython.view cimport array from cpython.mem cimport PyMem_Malloc, PyMem_Free IF UNAME_SYSNAME == "Windows": from . cimport _mswin as mswin ELSE: from posix cimport dlfcn from ._pkcs11_defn cimport * include '_errors.pyx' include '_utils.pyx' from . import types from .defaults import * from .exceptions import * from .constants import * from .mechanisms import * from .types import ( _CK_UTF8CHAR_to_str, _CK_VERSION_to_tuple, _CK_MECHANISM_TYPE_to_enum, PROTECTED_AUTH, ) # _funclist is used to keep the pointer to the list of functions, when lib() is invoked. # This is a global, as this object cannot be shared between Python and Cython classes # Due to this limitation, the current implementation limits the loading of the library # to one instance only, or to several instances of the same kind. cdef CK_FUNCTION_LIST *_funclist = NULL cdef class AttributeList: """ A list of CK_ATTRIBUTE objects. """ cdef CK_ATTRIBUTE *data """CK_ATTRIBUTE * representation of the data.""" cdef CK_ULONG count """Length of `data`.""" cdef _values def __cinit__(self, attrs): attrs = dict(attrs) self.count = count = len(attrs) self.data = PyMem_Malloc(count * sizeof(CK_ATTRIBUTE)) if not self.data: raise MemoryError() # Turn the values into bytes and store them so we have pointers # to them. self._values = [ (key, _pack_attribute(key, value)) for key, value in attrs.items() ] for index, (key, value) in enumerate(self._values): self.data[index].type = key self.data[index].pValue = value self.data[index].ulValueLen = len(value) def __dealloc__(self): PyMem_Free(self.data) cdef class MechanismWithParam: """ Python wrapper for a Mechanism with its parameter """ cdef CK_MECHANISM *data """The mechanism.""" cdef void *param """Reference to a pointer we might need to free.""" def __cinit__(self, *args): self.data = PyMem_Malloc(sizeof(CK_MECHANISM)) self.param = NULL def __init__(self, key_type, mapping, mechanism=None, param=None): if mechanism is None: try: mechanism = mapping[key_type] except KeyError: raise ArgumentsBad("No default mechanism for this key type. " "Please specify `mechanism`.") if not isinstance(mechanism, Mechanism): raise ArgumentsBad("`mechanism` must be a Mechanism.") # Possible types of parameters we might need to allocate # These are used to make assigning to the object we malloc() easier # FIXME: is there a better way to do this? cdef CK_RSA_PKCS_OAEP_PARAMS *oaep_params cdef CK_RSA_PKCS_PSS_PARAMS *pss_params cdef CK_ECDH1_DERIVE_PARAMS *ecdh1_params # Unpack mechanism parameters if mechanism is Mechanism.RSA_PKCS_OAEP: paramlen = sizeof(CK_RSA_PKCS_OAEP_PARAMS) self.param = oaep_params = \ PyMem_Malloc(paramlen) oaep_params.source = CKZ_DATA_SPECIFIED if param is None: param = DEFAULT_MECHANISM_PARAMS[mechanism] (oaep_params.hashAlg, oaep_params.mgf, source_data) = param if source_data is None: oaep_params.pSourceData = NULL oaep_params.ulSourceDataLen = 0 else: oaep_params.pSourceData = source_data oaep_params.ulSourceDataLen = len(source_data) elif mechanism in (Mechanism.RSA_PKCS_PSS, Mechanism.SHA1_RSA_PKCS_PSS, Mechanism.SHA224_RSA_PKCS_PSS, Mechanism.SHA256_RSA_PKCS_PSS, Mechanism.SHA384_RSA_PKCS_PSS, Mechanism.SHA512_RSA_PKCS_PSS): paramlen = sizeof(CK_RSA_PKCS_PSS_PARAMS) self.param = pss_params = \ PyMem_Malloc(paramlen) if param is None: # All PSS mechanisms have the same defaults param = DEFAULT_MECHANISM_PARAMS[Mechanism.RSA_PKCS_PSS] (pss_params.hashAlg, pss_params.mgf, pss_params.sLen) = param elif mechanism is Mechanism.ECDH1_DERIVE: paramlen = sizeof(CK_ECDH1_DERIVE_PARAMS) self.param = ecdh1_params = \ PyMem_Malloc(paramlen) (ecdh1_params.kdf, shared_data, public_data) = param if shared_data is None: ecdh1_params.pSharedData = NULL ecdh1_params.ulSharedDataLen = 0 else: ecdh1_params.pSharedData = shared_data ecdh1_params.ulSharedDataLen = len(shared_data) ecdh1_params.pPublicData = public_data ecdh1_params.ulPublicDataLen = len(public_data) elif isinstance(param, bytes): self.data.pParameter = param paramlen = len(param) elif param is None: self.data.pParameter = NULL paramlen = 0 else: raise ArgumentsBad("Unexpected argument to mechanism_param") self.data.mechanism = mechanism self.data.ulParameterLen = paramlen if self.param != NULL: self.data.pParameter = self.param def __dealloc__(self): PyMem_Free(self.data) PyMem_Free(self.param) class Slot(types.Slot): """Extend Slot with implementation.""" def get_token(self): cdef CK_SLOT_ID slot_id = self.slot_id cdef CK_TOKEN_INFO info with nogil: assertRV(_funclist.C_GetTokenInfo(slot_id, &info)) label = info.label[:sizeof(info.label)] serialNumber = info.serialNumber[:sizeof(info.serialNumber)] model = info.model[:sizeof(info.model)] manufacturerID = info.manufacturerID[:sizeof(info.manufacturerID)] return Token(self, label, serialNumber, model, manufacturerID, info.hardwareVersion, info.firmwareVersion, info.flags) def get_mechanisms(self): cdef CK_SLOT_ID slot_id = self.slot_id cdef CK_ULONG count with nogil: assertRV(_funclist.C_GetMechanismList(slot_id, NULL, &count)) if count == 0: return set() cdef CK_MECHANISM_TYPE [:] mechanisms = CK_ULONG_buffer(count) with nogil: assertRV(_funclist.C_GetMechanismList(slot_id, &mechanisms[0], &count)) return set(map(_CK_MECHANISM_TYPE_to_enum, mechanisms)) def get_mechanism_info(self, mechanism): cdef CK_SLOT_ID slot_id = self.slot_id cdef CK_MECHANISM_TYPE mech_type = mechanism cdef CK_MECHANISM_INFO info with nogil: assertRV(_funclist.C_GetMechanismInfo(slot_id, mech_type, &info)) return types.MechanismInfo(self, mechanism, **info) class Token(types.Token): """Extend Token with implementation.""" def open(self, rw=False, user_pin=None, so_pin=None): cdef CK_SLOT_ID slot_id = self.slot.slot_id cdef CK_SESSION_HANDLE handle cdef CK_FLAGS flags = CKF_SERIAL_SESSION cdef CK_USER_TYPE user_type cdef CK_UTF8CHAR *pin_data cdef CK_ULONG pin_length if rw: flags |= CKF_RW_SESSION if user_pin is not None and so_pin is not None: raise ArgumentsBad("Set either `user_pin` or `so_pin`") elif user_pin is PROTECTED_AUTH: pin = None user_type = CKU_USER elif so_pin is PROTECTED_AUTH: pin = None user_type = CKU_SO elif user_pin is not None: pin = user_pin.encode('utf-8') user_type = CKU_USER elif so_pin is not None: pin = so_pin.encode('utf-8') user_type = CKU_SO else: pin = None user_type = UserType.NOBODY with nogil: assertRV(_funclist.C_OpenSession(slot_id, flags, NULL, NULL, &handle)) if so_pin is PROTECTED_AUTH or user_pin is PROTECTED_AUTH: if self.flags & TokenFlag.PROTECTED_AUTHENTICATION_PATH: with nogil: assertRV(_funclist.C_Login(handle, user_type, NULL, 0)) else: raise ArgumentsBad("Protected authentication is not supported by loaded module") elif pin is not None: pin_data = pin pin_length = len(pin) with nogil: assertRV(_funclist.C_Login(handle, user_type, pin_data, pin_length)) return Session(self, handle, rw=rw, user_type=user_type) class SearchIter: """Iterate a search for objects on a session.""" def __init__(self, session, attrs): self.session = session template = AttributeList(attrs) self.session._operation_lock.acquire() self._active = True cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_ATTRIBUTE *attr_data = template.data cdef CK_ULONG attr_count = template.count with nogil: assertRV(_funclist.C_FindObjectsInit(handle, attr_data, attr_count)) def __iter__(self): return self def __next__(self): """Get the next object.""" cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_OBJECT_HANDLE obj cdef CK_ULONG count with nogil: assertRV(_funclist.C_FindObjects(handle, &obj, 1, &count)) if count == 0: self._finalize() raise StopIteration() else: return Object._make(self.session, obj) def __del__(self): """Close the search.""" self._finalize() def _finalize(self): """Finish the operation.""" cdef CK_SESSION_HANDLE handle = self.session._handle if self._active: self._active = False with nogil: assertRV(_funclist.C_FindObjectsFinal(handle)) self.session._operation_lock.release() def merge_templates(default_template, *user_templates): template = default_template.copy() for user_template in user_templates: if user_template is not None: template.update(user_template) return { key: value for key, value in template.items() if value is not DEFAULT } class Session(types.Session): """Extend Session with implementation.""" def close(self): cdef CK_OBJECT_HANDLE handle = self._handle if self.user_type != UserType.NOBODY: with nogil: assertRV(_funclist.C_Logout(handle)) with nogil: assertRV(_funclist.C_CloseSession(handle)) def get_objects(self, attrs=None): return SearchIter(self, attrs or {}) def create_object(self, attrs): template = AttributeList(attrs) cdef CK_OBJECT_HANDLE handle = self._handle cdef CK_ATTRIBUTE *attr_data = template.data cdef CK_ULONG attr_count = template.count cdef CK_OBJECT_HANDLE new with nogil: assertRV(_funclist.C_CreateObject(handle, attr_data, attr_count, &new)) return Object._make(self, new) def create_domain_parameters(self, key_type, attrs, local=False, store=False): if local and store: raise ArgumentsBad("Cannot set both `local` and `store`") attrs = dict(attrs) attrs[Attribute.CLASS] = ObjectClass.DOMAIN_PARAMETERS attrs[Attribute.KEY_TYPE] = key_type attrs[Attribute.TOKEN] = store if local: return DomainParameters(self, None, attrs) else: return self.create_object(attrs) def generate_domain_parameters(self, key_type, param_length, store=False, mechanism=None, mechanism_param=None, template=None): if not isinstance(key_type, KeyType): raise ArgumentsBad("`key_type` must be KeyType.") if not isinstance(param_length, int): raise ArgumentsBad("`param_length` is the length in bits.") mech = MechanismWithParam( key_type, DEFAULT_PARAM_GENERATE_MECHANISMS, mechanism, mechanism_param) template_ = { Attribute.CLASS: ObjectClass.DOMAIN_PARAMETERS, Attribute.TOKEN: store, Attribute.PRIME_BITS: param_length, } attrs = AttributeList(merge_templates(template_, template)) cdef CK_SESSION_HANDLE handle = self._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_ATTRIBUTE *attr_data = attrs.data cdef CK_ULONG attr_count = attrs.count cdef CK_OBJECT_HANDLE obj with nogil: assertRV(_funclist.C_GenerateKey(handle, mech_data, attr_data, attr_count, &obj)) return Object._make(self, obj) def generate_key(self, key_type, key_length=None, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, template=None): if not isinstance(key_type, KeyType): raise ArgumentsBad("`key_type` must be KeyType.") if key_length is not None and not isinstance(key_length, int): raise ArgumentsBad("`key_length` is the length in bits.") if capabilities is None: try: capabilities = DEFAULT_KEY_CAPABILITIES[key_type] except KeyError: raise ArgumentsBad("No default capabilities for this key " "type. Please specify `capabilities`.") mech = MechanismWithParam( key_type, DEFAULT_GENERATE_MECHANISMS, mechanism, mechanism_param) # Build attributes template_ = { Attribute.CLASS: ObjectClass.SECRET_KEY, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, Attribute.PRIVATE: True, Attribute.SENSITIVE: True, # Capabilities Attribute.ENCRYPT: MechanismFlag.ENCRYPT & capabilities, Attribute.DECRYPT: MechanismFlag.DECRYPT & capabilities, Attribute.WRAP: MechanismFlag.WRAP & capabilities, Attribute.UNWRAP: MechanismFlag.UNWRAP & capabilities, Attribute.SIGN: MechanismFlag.SIGN & capabilities, Attribute.VERIFY: MechanismFlag.VERIFY & capabilities, Attribute.DERIVE: MechanismFlag.DERIVE & capabilities, } if key_type is KeyType.AES: if key_length is None: raise ArgumentsBad("Must provide `key_length'") template_[Attribute.VALUE_LEN] = key_length // 8 # In bytes attrs = AttributeList(merge_templates(template_, template)) cdef CK_SESSION_HANDLE handle = self._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_ATTRIBUTE *attr_data = attrs.data cdef CK_ULONG attr_count = attrs.count cdef CK_OBJECT_HANDLE key with nogil: assertRV(_funclist.C_GenerateKey(handle, mech_data, attr_data, attr_count, &key)) return Object._make(self, key) def _generate_keypair(self, key_type, key_length=None, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, public_template=None, private_template=None): if not isinstance(key_type, KeyType): raise ArgumentsBad("`key_type` must be KeyType.") if key_length is not None and not isinstance(key_length, int): raise ArgumentsBad("`key_length` is the length in bits.") if capabilities is None: try: capabilities = DEFAULT_KEY_CAPABILITIES[key_type] except KeyError: raise ArgumentsBad("No default capabilities for this key " "type. Please specify `capabilities`.") mech = MechanismWithParam( key_type, DEFAULT_GENERATE_MECHANISMS, mechanism, mechanism_param) # Build attributes public_template_ = { Attribute.CLASS: ObjectClass.PUBLIC_KEY, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, # Capabilities Attribute.ENCRYPT: MechanismFlag.ENCRYPT & capabilities, Attribute.WRAP: MechanismFlag.WRAP & capabilities, Attribute.VERIFY: MechanismFlag.VERIFY & capabilities, } if key_type is KeyType.RSA: if key_length is None: raise ArgumentsBad("Must provide `key_length'") # Some PKCS#11 implementations don't default this, it makes sense # to do it here public_template_.update({ Attribute.PUBLIC_EXPONENT: b'\1\0\1', Attribute.MODULUS_BITS: key_length, }) public_attrs = AttributeList(merge_templates(public_template_, public_template)) private_template_ = { Attribute.CLASS: ObjectClass.PRIVATE_KEY, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, Attribute.PRIVATE: True, Attribute.SENSITIVE: True, # Capabilities Attribute.DECRYPT: MechanismFlag.DECRYPT & capabilities, Attribute.UNWRAP: MechanismFlag.UNWRAP & capabilities, Attribute.SIGN: MechanismFlag.SIGN & capabilities, Attribute.DERIVE: MechanismFlag.DERIVE & capabilities, } private_attrs = AttributeList(merge_templates(private_template_, private_template)) cdef CK_SESSION_HANDLE handle = self._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_ATTRIBUTE *public_attr_data = public_attrs.data cdef CK_ULONG public_attr_count = public_attrs.count cdef CK_ATTRIBUTE *private_attr_data = private_attrs.data cdef CK_ULONG private_attr_count = private_attrs.count cdef CK_OBJECT_HANDLE public_key cdef CK_OBJECT_HANDLE private_key with nogil: assertRV(_funclist.C_GenerateKeyPair(handle, mech_data, public_attr_data, public_attr_count, private_attr_data, private_attr_count, &public_key, &private_key)) return (Object._make(self, public_key), Object._make(self, private_key)) def seed_random(self, seed): cdef CK_SESSION_HANDLE handle = self._handle cdef CK_BYTE *seed_data = seed cdef CK_ULONG seed_len = len(seed) with nogil: assertRV(_funclist.C_SeedRandom(handle, seed_data, seed_len)) def generate_random(self, nbits): cdef CK_SESSION_HANDLE handle = self._handle cdef CK_ULONG length = nbits // 8 cdef CK_CHAR [:] random = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_GenerateRandom(handle, &random[0], length)) return bytes(random) def _digest(self, data, mechanism=None, mechanism_param=None): mech = MechanismWithParam(None, {}, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_BYTE *data_ptr = data cdef CK_ULONG data_len = len(data) cdef CK_BYTE [:] digest cdef CK_ULONG length with self._operation_lock: with nogil: assertRV(_funclist.C_DigestInit(handle, mech_data)) # Run once to get the length assertRV(_funclist.C_Digest(handle, data_ptr, data_len, NULL, &length)) digest = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_Digest(handle, data_ptr, data_len, &digest[0], &length)) return bytes(digest[:length]) def _digest_generator(self, data, mechanism=None, mechanism_param=None): mech = MechanismWithParam(None, {}, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key cdef CK_BYTE *data_ptr cdef CK_ULONG data_len cdef CK_BYTE [:] digest cdef CK_ULONG length with self._operation_lock: with nogil: assertRV(_funclist.C_DigestInit(handle, mech_data)) for block in data: if isinstance(block, types.Key): key = block._handle with nogil: assertRV(_funclist.C_DigestKey(handle, key)) else: data_ptr = block data_len = len(block) with nogil: assertRV(_funclist.C_DigestUpdate(handle, data_ptr, data_len)) # Run once to get the length with nogil: assertRV(_funclist.C_DigestFinal(handle, NULL, &length)) digest = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_DigestFinal(handle, &digest[0], &length)) return bytes(digest[:length]) class Object(types.Object): """Expand Object with an implementation.""" @classmethod def _make(cls, *args, **kwargs): """ Make an object with the right bases for its class and capabilities. """ # Make a version of ourselves we can introspect self = cls(*args, **kwargs) try: # Determine a list of base classes to manufacture our class with # FIXME: we should really request all of these attributes in # one go object_class = self[Attribute.CLASS] bases = (_CLASS_MAP[object_class],) # Build a list of mixins for this new class for attribute, mixin in ( (Attribute.ENCRYPT, EncryptMixin), (Attribute.DECRYPT, DecryptMixin), (Attribute.SIGN, SignMixin), (Attribute.VERIFY, VerifyMixin), (Attribute.WRAP, WrapMixin), (Attribute.UNWRAP, UnwrapMixin), (Attribute.DERIVE, DeriveMixin), ): try: if self[attribute]: bases += (mixin,) # nFast returns FunctionFailed when you request an attribute # it doesn't like. except (AttributeTypeInvalid, FunctionFailed): pass bases += (cls,) # Manufacture a class with the right capabilities. klass = type(bases[0].__name__, bases, {}) return klass(*args, **kwargs) except KeyError: return self def __getitem__(self, key): cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_OBJECT_HANDLE obj = self._handle cdef CK_ATTRIBUTE template template.type = key template.pValue = NULL template.ulValueLen = 0 # Find out the attribute size with nogil: assertRV(_funclist.C_GetAttributeValue(handle, obj, &template, 1)) if template.ulValueLen == 0: return _unpack_attributes(key, b'') # Put a buffer of the right length in place cdef CK_CHAR [:] value = CK_BYTE_buffer(template.ulValueLen) template.pValue = &value[0] # Request the value with nogil: assertRV(_funclist.C_GetAttributeValue(handle, obj, &template, 1)) return _unpack_attributes(key, value) def __setitem__(self, key, value): cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_OBJECT_HANDLE obj = self._handle cdef CK_ATTRIBUTE template value = _pack_attribute(key, value) template.type = key template.pValue = value template.ulValueLen = len(value) with nogil: assertRV(_funclist.C_SetAttributeValue(handle, obj, &template, 1)) def copy(self, attrs): template = AttributeList(attrs) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_OBJECT_HANDLE obj = self._handle cdef CK_ATTRIBUTE *attr_data = template.data cdef CK_ULONG attr_count = template.count cdef CK_OBJECT_HANDLE new with nogil: assertRV(_funclist.C_CopyObject(handle, obj, attr_data, attr_count, &new)) return Object._make(self.session, new) def destroy(self): cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_OBJECT_HANDLE obj = self._handle with nogil: assertRV(_funclist.C_DestroyObject(handle, obj)) class SecretKey(types.SecretKey): pass class PublicKey(types.PublicKey): pass class PrivateKey(types.PrivateKey): pass class DomainParameters(types.DomainParameters): def generate_keypair(self, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, public_template=None, private_template=None): if capabilities is None: try: capabilities = DEFAULT_KEY_CAPABILITIES[self.key_type] except KeyError: raise ArgumentsBad("No default capabilities for this key " "type. Please specify `capabilities`.") mech = MechanismWithParam( self.key_type, DEFAULT_GENERATE_MECHANISMS, mechanism, mechanism_param) # Build attributes public_template_ = { Attribute.CLASS: ObjectClass.PUBLIC_KEY, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, # Capabilities Attribute.ENCRYPT: MechanismFlag.ENCRYPT & capabilities, Attribute.WRAP: MechanismFlag.WRAP & capabilities, Attribute.VERIFY: MechanismFlag.VERIFY & capabilities, } # Copy in our domain parameters. # Not all parameters are appropriate for all domains. for attribute in ( Attribute.BASE, Attribute.PRIME, Attribute.SUBPRIME, Attribute.EC_PARAMS, ): try: public_template_[attribute] = self[attribute] # nFast returns FunctionFailed for parameters it doesn't like except (AttributeTypeInvalid, FunctionFailed): pass public_attrs = AttributeList(merge_templates(public_template_, public_template)) private_template_ = { Attribute.CLASS: ObjectClass.PRIVATE_KEY, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, Attribute.PRIVATE: True, Attribute.SENSITIVE: True, # Capabilities Attribute.DECRYPT: MechanismFlag.DECRYPT & capabilities, Attribute.UNWRAP: MechanismFlag.UNWRAP & capabilities, Attribute.SIGN: MechanismFlag.SIGN & capabilities, Attribute.DERIVE: MechanismFlag.DERIVE & capabilities, } private_attrs = AttributeList(merge_templates(private_template_, private_template)) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_ATTRIBUTE *public_attr_data = public_attrs.data cdef CK_ULONG public_attr_count = public_attrs.count cdef CK_ATTRIBUTE *private_attr_data = private_attrs.data cdef CK_ULONG private_attr_count = private_attrs.count cdef CK_OBJECT_HANDLE public_key cdef CK_OBJECT_HANDLE private_key with nogil: assertRV(_funclist.C_GenerateKeyPair(handle, mech_data, public_attr_data, public_attr_count, private_attr_data, private_attr_count, &public_key, &private_key)) return (Object._make(self.session, public_key), Object._make(self.session, private_key)) class Certificate(types.Certificate): pass class EncryptMixin(types.EncryptMixin): """Expand EncryptMixin with an implementation.""" def _encrypt(self, data, mechanism=None, mechanism_param=None): """ Non chunking encrypt. Needed for some mechanisms. """ mech = MechanismWithParam( self.key_type, DEFAULT_ENCRYPT_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr = data cdef CK_ULONG data_len = len(data) cdef CK_BYTE [:] ciphertext cdef CK_ULONG length with self.session._operation_lock: with nogil: assertRV(_funclist.C_EncryptInit(handle, mech_data, key)) # Call to find out the buffer length with nogil: assertRV(_funclist.C_Encrypt(handle, data_ptr, data_len, NULL, &length)) ciphertext = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_Encrypt(handle, data_ptr, data_len, &ciphertext[0], &length)) return bytes(ciphertext[:length]) def _encrypt_generator(self, data, mechanism=None, mechanism_param=None, buffer_size=8192): """ Do chunked encryption. Failing to consume the generator will raise GeneratorExit when it garbage collects. This will release the lock, but you'll still be in the middle of an operation, and all future operations will raise OperationActive, see tests/test_iterators.py:test_close_iterators(). FIXME: cancel the operation when we exit the generator early. """ mech = MechanismWithParam( self.key_type, DEFAULT_ENCRYPT_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr cdef CK_ULONG data_len cdef CK_ULONG length cdef CK_BYTE [:] part_out = CK_BYTE_buffer(buffer_size) with self.session._operation_lock: with nogil: assertRV(_funclist.C_EncryptInit(handle, mech_data, key)) for part_in in data: if not part_in: continue data_ptr = part_in data_len = len(part_in) length = buffer_size with nogil: assertRV(_funclist.C_EncryptUpdate(handle, data_ptr, data_len, &part_out[0], &length)) yield bytes(part_out[:length]) # Finalize # We assume the buffer is much bigger than the block size length = buffer_size with nogil: assertRV(_funclist.C_EncryptFinal(handle, &part_out[0], &length)) yield bytes(part_out[:length]) class DecryptMixin(types.DecryptMixin): """Expand DecryptMixin with an implementation.""" def _decrypt(self, data, mechanism=None, mechanism_param=None): """Non chunking decrypt.""" mech = MechanismWithParam( self.key_type, DEFAULT_ENCRYPT_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr = data cdef CK_ULONG data_len = len(data) cdef CK_BYTE [:] plaintext cdef CK_ULONG length with self.session._operation_lock: with nogil: assertRV(_funclist.C_DecryptInit(handle, mech_data, key)) # Call to find out the buffer length with nogil: assertRV(_funclist.C_Decrypt(handle, data_ptr, data_len, NULL, &length)) plaintext = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_Decrypt(handle, data_ptr, data_len, &plaintext[0], &length)) return bytes(plaintext[:length]) def _decrypt_generator(self, data, mechanism=None, mechanism_param=None, buffer_size=8192): """ Chunking decrypt. Failing to consume the generator will raise GeneratorExit when it garbage collects. This will release the lock, but you'll still be in the middle of an operation, and all future operations will raise OperationActive, see tests/test_iterators.py:test_close_iterators(). FIXME: cancel the operation when we exit the generator early. """ mech = MechanismWithParam( self.key_type, DEFAULT_ENCRYPT_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr cdef CK_ULONG data_len cdef CK_ULONG length cdef CK_BYTE [:] part_out = CK_BYTE_buffer(buffer_size) with self.session._operation_lock: with nogil: assertRV(_funclist.C_DecryptInit(handle, mech_data, key)) for part_in in data: if not part_in: continue data_ptr = part_in data_len = len(part_in) length = buffer_size with nogil: assertRV(_funclist.C_DecryptUpdate(handle, data_ptr, data_len, &part_out[0], &length)) yield bytes(part_out[:length]) # Finalize # We assume the buffer is much bigger than the block size length = buffer_size with nogil: assertRV(_funclist.C_DecryptFinal(handle, &part_out[0], &length)) yield bytes(part_out[:length]) class SignMixin(types.SignMixin): """Expand SignMixin with an implementation.""" def _sign(self, data, mechanism=None, mechanism_param=None): mech = MechanismWithParam( self.key_type, DEFAULT_SIGN_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr = data cdef CK_ULONG data_len = len(data) cdef CK_BYTE [:] signature cdef CK_ULONG length with self.session._operation_lock: with nogil: assertRV(_funclist.C_SignInit(handle, mech_data, key)) # Call to find out the buffer length assertRV(_funclist.C_Sign(handle, data_ptr, data_len, NULL, &length)) signature = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_Sign(handle, data_ptr, data_len, &signature[0], &length)) return bytes(signature[:length]) def _sign_generator(self, data, mechanism=None, mechanism_param=None): mech = MechanismWithParam( self.key_type, DEFAULT_SIGN_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr cdef CK_ULONG data_len cdef CK_BYTE [:] signature cdef CK_ULONG length with self.session._operation_lock: with nogil: assertRV(_funclist.C_SignInit(handle, mech_data, key)) for part_in in data: if not part_in: continue data_ptr = part_in data_len = len(part_in) with nogil: assertRV(_funclist.C_SignUpdate(handle, data_ptr, data_len)) # Finalize # Call to find out the buffer length with nogil: assertRV(_funclist.C_SignFinal(handle, NULL, &length)) signature = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_SignFinal(handle, &signature[0], &length)) return bytes(signature[:length]) class VerifyMixin(types.VerifyMixin): """Expand VerifyMixin with an implementation.""" def _verify(self, data, signature, mechanism=None, mechanism_param=None): mech = MechanismWithParam( self.key_type, DEFAULT_SIGN_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr = data cdef CK_ULONG data_len = len(data) cdef CK_BYTE *sig_ptr = signature cdef CK_ULONG sig_len = len(signature) with self.session._operation_lock: with nogil: assertRV(_funclist.C_VerifyInit(handle, mech_data, key)) assertRV(_funclist.C_Verify(handle, data_ptr, data_len, sig_ptr, sig_len)) def _verify_generator(self, data, signature, mechanism=None, mechanism_param=None): mech = MechanismWithParam( self.key_type, DEFAULT_SIGN_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE key = self._handle cdef CK_BYTE *data_ptr cdef CK_ULONG data_len cdef CK_BYTE *sig_ptr = signature cdef CK_ULONG sig_len = len(signature) with self.session._operation_lock: with nogil: assertRV(_funclist.C_VerifyInit(handle, mech_data, key)) for part_in in data: if not part_in: continue data_ptr = part_in data_len = len(part_in) with nogil: assertRV(_funclist.C_VerifyUpdate(handle, data_ptr, data_len)) with nogil: assertRV(_funclist.C_VerifyFinal(handle, sig_ptr, sig_len)) class WrapMixin(types.WrapMixin): """Expand WrapMixin with an implementation.""" def wrap_key(self, key, mechanism=None, mechanism_param=None): if not isinstance(key, types.Key): raise ArgumentsBad("`key` must be a Key.") mech = MechanismWithParam( self.key_type, DEFAULT_WRAP_MECHANISMS, mechanism, mechanism_param) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE wrapping_key = self._handle cdef CK_OBJECT_HANDLE key_to_wrap = key._handle cdef CK_ULONG length # Find out how many bytes we need to allocate with nogil: assertRV(_funclist.C_WrapKey(handle, mech_data, wrapping_key, key_to_wrap, NULL, &length)) cdef CK_BYTE [:] data = CK_BYTE_buffer(length) with nogil: assertRV(_funclist.C_WrapKey(handle, mech_data, wrapping_key, key_to_wrap, &data[0], &length)) return bytes(data[:length]) class UnwrapMixin(types.UnwrapMixin): """Expand UnwrapMixin with an implementation.""" def unwrap_key(self, object_class, key_type, key_data, id=None, label=None, mechanism=None, mechanism_param=None, store=False, capabilities=None, template=None): if not isinstance(object_class, ObjectClass): raise ArgumentsBad("`object_class` must be ObjectClass.") if not isinstance(key_type, KeyType): raise ArgumentsBad("`key_type` must be KeyType.") if capabilities is None: try: capabilities = DEFAULT_KEY_CAPABILITIES[key_type] except KeyError: raise ArgumentsBad("No default capabilities for this key " "type. Please specify `capabilities`.") mech = MechanismWithParam( self.key_type, DEFAULT_WRAP_MECHANISMS, mechanism, mechanism_param) # Build attributes template_ = { Attribute.CLASS: object_class, Attribute.KEY_TYPE: key_type, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, # Capabilities Attribute.ENCRYPT: MechanismFlag.ENCRYPT & capabilities, Attribute.DECRYPT: MechanismFlag.DECRYPT & capabilities, Attribute.WRAP: MechanismFlag.WRAP & capabilities, Attribute.UNWRAP: MechanismFlag.UNWRAP & capabilities, Attribute.SIGN: MechanismFlag.SIGN & capabilities, Attribute.VERIFY: MechanismFlag.VERIFY & capabilities, Attribute.DERIVE: MechanismFlag.DERIVE & capabilities, } attrs = AttributeList(merge_templates(template_, template)) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE unwrapping_key = self._handle cdef CK_BYTE *wrapped_key_ptr = key_data cdef CK_ULONG wrapped_key_len = len(key_data) cdef CK_ATTRIBUTE *attr_data = attrs.data cdef CK_ULONG attr_count = attrs.count cdef CK_OBJECT_HANDLE key with nogil: assertRV(_funclist.C_UnwrapKey(handle, mech_data, unwrapping_key, wrapped_key_ptr, wrapped_key_len, attr_data, attr_count, &key)) return Object._make(self.session, key) class DeriveMixin(types.DeriveMixin): """Expand DeriveMixin with an implementation.""" def derive_key(self, key_type, key_length, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, template=None): if not isinstance(key_type, KeyType): raise ArgumentsBad("`key_type` must be KeyType.") if not isinstance(key_length, int): raise ArgumentsBad("`key_length` is the length in bits.") if capabilities is None: try: capabilities = DEFAULT_KEY_CAPABILITIES[key_type] except KeyError: raise ArgumentsBad("No default capabilities for this key " "type. Please specify `capabilities`.") mech = MechanismWithParam( self.key_type, DEFAULT_DERIVE_MECHANISMS, mechanism, mechanism_param) # Build attributes template_ = { Attribute.CLASS: ObjectClass.SECRET_KEY, Attribute.KEY_TYPE: key_type, Attribute.ID: id or b'', Attribute.LABEL: label or '', Attribute.TOKEN: store, Attribute.VALUE_LEN: key_length // 8, # In bytes Attribute.PRIVATE: True, Attribute.SENSITIVE: True, # Capabilities Attribute.ENCRYPT: MechanismFlag.ENCRYPT & capabilities, Attribute.DECRYPT: MechanismFlag.DECRYPT & capabilities, Attribute.WRAP: MechanismFlag.WRAP & capabilities, Attribute.UNWRAP: MechanismFlag.UNWRAP & capabilities, Attribute.SIGN: MechanismFlag.SIGN & capabilities, Attribute.VERIFY: MechanismFlag.VERIFY & capabilities, Attribute.DERIVE: MechanismFlag.DERIVE & capabilities, } attrs = AttributeList(merge_templates(template_, template)) cdef CK_SESSION_HANDLE handle = self.session._handle cdef CK_MECHANISM *mech_data = mech.data cdef CK_OBJECT_HANDLE src_key = self._handle cdef CK_ATTRIBUTE *attr_data = attrs.data cdef CK_ULONG attr_count = attrs.count cdef CK_OBJECT_HANDLE key with nogil: assertRV(_funclist.C_DeriveKey(handle, mech_data, src_key, attr_data, attr_count, &key)) return Object._make(self.session, key) _CLASS_MAP = { ObjectClass.SECRET_KEY: SecretKey, ObjectClass.PUBLIC_KEY: PublicKey, ObjectClass.PRIVATE_KEY: PrivateKey, ObjectClass.DOMAIN_PARAMETERS: DomainParameters, ObjectClass.CERTIFICATE: Certificate, } cdef class lib: """ Main entry point. This class needs to be defined cdef, so it can't shadow a class in pkcs11.types. """ cdef public str so cdef public str manufacturer_id cdef public str library_description cdef public tuple cryptoki_version cdef public tuple library_version IF UNAME_SYSNAME == "Windows": cdef mswin.HMODULE _handle ELSE: cdef void *_handle cdef _load_pkcs11_lib(self, so) with gil: """Load a PKCS#11 library, and extract function calls. This method will dynamically load a PKCS11 library, and attempt to resolve the symbol 'C_GetFunctionList()'. Once found, the entry point is called to populate an internal table of function pointers. This is a private method, and must never be called directly. Called when a new lib class is instantiated. :param so: the path to a valid PKCS#11 library :type so: str :raises: RuntimeError or PKCS11Error :rtype: None """ # to keep a pointer to the C_GetFunctionList address returned by dlsym() cdef C_GetFunctionList_ptr C_GetFunctionList IF UNAME_SYSNAME == "Windows": self._handle = mswin.LoadLibraryW(so) if self._handle == NULL: raise RuntimeError("Cannot open library at {}: {}".format(so, mswin.winerror(so))) if self._handle != NULL: C_GetFunctionList = mswin.GetProcAddress(self._handle, 'C_GetFunctionList') if C_GetFunctionList == NULL: raise RuntimeError("{} is not a PKCS#11 library: {}".format(so, mswin.winerror(so))) ELSE: self._handle = dlfcn.dlopen(so.encode('utf-8'), dlfcn.RTLD_LAZY | dlfcn.RTLD_LOCAL) if self._handle == NULL: raise RuntimeError(dlfcn.dlerror()) C_GetFunctionList = dlfcn.dlsym(self._handle, 'C_GetFunctionList') if C_GetFunctionList == NULL: raise RuntimeError("{} is not a PKCS#11 library: {}".format(so, dlfcn.dlerror())) with nogil: assertRV(C_GetFunctionList(&_funclist)) cdef _unload_pkcs11_lib(self) with gil: """Unload a PKCS#11 library. This method will dynamically unload a PKCS11 library. This is a private method, and must never be called directly. Called when a lib instance is destroyed. """ IF UNAME_SYSNAME == "Windows": if self._handle != NULL: mswin.FreeLibrary(self._handle) ELSE: if self._handle != NULL: dlfcn.dlclose(self._handle) def __cinit__(self, so): self._load_pkcs11_lib(so) # at this point, _funclist contains all function pointers to the library with nogil: assertRV(_funclist.C_Initialize(NULL)) def __init__(self, so): self.so = so cdef CK_INFO info with nogil: assertRV(_funclist.C_GetInfo(&info)) manufacturerID = info.manufacturerID[:sizeof(info.manufacturerID)] libraryDescription = info.libraryDescription[:sizeof(info.libraryDescription)] self.manufacturer_id = _CK_UTF8CHAR_to_str(manufacturerID) self.library_description = _CK_UTF8CHAR_to_str(libraryDescription) self.cryptoki_version = _CK_VERSION_to_tuple(info.cryptokiVersion) self.library_version = _CK_VERSION_to_tuple(info.libraryVersion) def __str__(self): return '\n'.join(( "Library: %s" % self.so, "Manufacturer ID: %s" % self.manufacturer_id, "Library Description: %s" % self.library_description, "Cryptoki Version: %s.%s" % self.cryptoki_version, "Library Version: %s.%s" % self.library_version, )) def __repr__(self): return ''.format( so=self.so) def get_slots(self, token_present=False): """Get all slots.""" cdef CK_BBOOL present = token_present cdef CK_ULONG count with nogil: assertRV(_funclist.C_GetSlotList(present, NULL, &count)) if count == 0: return [] cdef CK_SLOT_ID [:] slot_list = CK_ULONG_buffer(count) with nogil: assertRV(_funclist.C_GetSlotList(present, &slot_list[0], &count)) cdef CK_SLOT_ID slot_id cdef CK_SLOT_INFO info slots = [] for slot_id in slot_list: with nogil: assertRV(_funclist.C_GetSlotInfo(slot_id, &info)) slotDescription = info.slotDescription[:sizeof(info.slotDescription)] manufacturerID = info.manufacturerID[:sizeof(info.manufacturerID)] slots.append( Slot(self, slot_id, slotDescription, manufacturerID, info.hardwareVersion, info.firmwareVersion, info.flags) ) return slots def get_tokens(self, token_label=None, token_serial=None, token_flags=None, slot_flags=None, mechanisms=None): """Search for a token matching the parameters.""" for slot in self.get_slots(): try: token = slot.get_token() token_mechanisms = slot.get_mechanisms() if token_label is not None and \ token.label != token_label: continue if token_serial is not None and \ token.serial != token_serial: continue if token_flags is not None and \ not token.flags & token_flags: continue if slot_flags is not None and \ not slot.flags & slot_flags: continue if mechanisms is not None and \ set(mechanisms) not in token_mechanisms: continue yield token except (TokenNotPresent, TokenNotRecognised): continue def get_token(self, **kwargs): """Get a single token.""" iterator = self.get_tokens(**kwargs) try: token = next(iterator) except StopIteration: raise NoSuchToken("No token matching %s" % kwargs) try: next(iterator) raise MultipleTokensReturned( "More than 1 token matches %s" % kwargs) except StopIteration: return token def reinitialize(self): if _funclist != NULL: with nogil: assertRV(_funclist.C_Finalize(NULL)) assertRV(_funclist.C_Initialize(NULL)) def __dealloc__(self): if _funclist != NULL: with nogil: assertRV(_funclist.C_Finalize(NULL)) self._unload_pkcs11_lib() python-pkcs11-0.7.0/python_pkcs11.egg-info/0000775000372000037200000000000013717606456021215 5ustar travistravis00000000000000python-pkcs11-0.7.0/python_pkcs11.egg-info/PKG-INFO0000664000372000037200000004514613717606455022323 0ustar travistravis00000000000000Metadata-Version: 1.1 Name: python-pkcs11 Version: 0.7.0 Summary: PKCS#11 (Cryptoki) support for Python Home-page: https://github.com/danni/python-pkcs11 Author: Danielle Madeley Author-email: danielle@madeley.id.au License: UNKNOWN Description: Python PKCS#11 - High Level Wrapper API ======================================= A high level, "more Pythonic" interface to the PKCS#11 (Cryptoki) standard to support HSM and Smartcard devices in Python. The interface is designed to follow the logical structure of a HSM, with useful defaults for obscurely documented parameters. Many APIs will optionally accept iterables and act as generators, allowing you to stream large data blocks for symmetric encryption. python-pkcs11 also includes numerous utility functions to convert between PKCS #11 data structures and common interchange formats including PKCS #1 and X.509. python-pkcs11 is fully documented and has a full integration test suite for all features, with continuous integration against multiple HSM platforms including: * Thales nCipher * Opencryptoki TPM * OpenSC/Smartcard-HSM/Nitrokey HSM Source: https://github.com/danni/python-pkcs11 Documentation: http://python-pkcs11.readthedocs.io/en/latest/ Getting Started --------------- Install from Pip: :: pip install python-pkcs11 Or build from source: :: python setup.py build Assuming your PKCS#11 library is set as `PKCS11_MODULE` and contains a token named `DEMO`: AES ~~~ :: import pkcs11 # Initialise our PKCS#11 library lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an AES key in this session key = session.generate_key(pkcs11.KeyType.AES, 256) # Get an initialisation vector iv = session.generate_random(128) # AES blocks are fixed at 128 bits # Encrypt our data crypttext = key.encrypt(data, mechanism_param=iv) 3DES ~~~~ :: import pkcs11 # Initialise our PKCS#11 library lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate a DES key in this session key = session.generate_key(pkcs11.KeyType.DES3) # Get an initialisation vector iv = session.generate_random(64) # DES blocks are fixed at 64 bits # Encrypt our data crypttext = key.encrypt(data, mechanism_param=iv) RSA ~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an RSA keypair in this session pub, priv = session.generate_keypair(pkcs11.KeyType.RSA, 2048) # Encrypt as one block crypttext = pub.encrypt(data) DSA ~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an DSA keypair in this session pub, priv = session.generate_keypair(pkcs11.KeyType.DSA, 1024) # Sign signature = priv.sign(data) ECDSA ~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an EC keypair in this session from a named curve ecparams = session.create_domain_parameters( pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: pkcs11.util.ec.encode_named_curve_parameters('prime256v1'), }, local=True) pub, priv = ecparams.generate_keypair() # Sign signature = priv.sign(data) Diffie-Hellman ~~~~~~~~~~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') with token.open() as session: # Given shared Diffie-Hellman parameters parameters = session.create_domain_parameters(pkcs11.KeyType.DH, { pkcs11.Attribute.PRIME: prime, # Diffie-Hellman parameters pkcs11.Attribute.BASE: base, }) # Generate a DH key pair from the public parameters public, private = parameters.generate_keypair() # Share the public half of it with our other party. _network_.write(public[Attribute.VALUE]) # And get their shared value other_value = _network_.read() # Derive a shared session key with perfect forward secrecy session_key = private.derive_key( pkcs11.KeyType.AES, 128, mechanism_param=other_value) Elliptic-Curve Diffie-Hellman ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') with token.open() as session: # Given DER encocded EC parameters, e.g. from # openssl ecparam -outform der -name parameters = session.create_domain_parameters(pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: ecparams, }) # Generate a DH key pair from the public parameters public, private = parameters.generate_keypair() # Share the public half of it with our other party. _network_.write(public[pkcs11.Attribute.EC_POINT]) # And get their shared value other_value = _network_.read() # Derive a shared session key session_key = private.derive_key( pkcs11.KeyType.AES, 128, mechanism_param=(pkcs11.KDF.NULL, None, other_value)) Tested Compatibility -------------------- +------------------------------+--------------+-----------------+--------------+-------------------+ | Functionality | SoftHSMv2 | Thales nCipher | Opencryptoki | OpenSC (Nitrokey) | +==============================+==============+=================+==============+===================+ | Get Slots/Tokens | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Get Mechanisms | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Initialize token | Not implemented | +------------------------------+-------------------------------------------------------------------+ | Slot events | Not implemented | +------------------------------+-------------------------------------------------------------------+ | Alternative authentication | Not implemented | | path | | +------------------------------+-------------------------------------------------------------------+ | `Always authenticate` keys | Not implemented | +-------------+----------------+--------------+-----------------+--------------+-------------------+ | Create/Copy | Keys | Works | Works | Errors | Create | | +----------------+--------------+-----------------+--------------+-------------------+ | | Certificates | Caveats [1]_ | Caveats [1]_ | Caveats [1]_ | ? | | +----------------+--------------+-----------------+--------------+-------------------+ | | Domain Params | Caveats [1]_ | Caveats [1]_ | ? | N/A | +-------------+----------------+--------------+-----------------+--------------+-------------------+ | Destroy Object | Works | N/A | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Generate Random | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Seed Random | Works | N/A | N/A | N/A | +------------------------------+--------------+-----------------+--------------+-------------------+ | Digest (Data & Keys) | Works | Caveats [2]_ | Works | Works | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | AES | Generate key | Works | Works | Works | N/A | | +---------------------+--------------+-----------------+--------------+ | | | Encrypt/Decrypt | Works | Works | Works | | | +---------------------+--------------+-----------------+--------------+ | | | Wrap/Unwrap | ? [3]_ | Works | Errors | | | +---------------------+--------------+-----------------+--------------+ | | | Sign/Verify | Works | Works [4]_ | N/A | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DES2/ | Generate key | Works | Works | Works | N/A | | DES3 +---------------------+--------------+-----------------+--------------+ | | | Encrypt/Decrypt | Works | Works | Works | | | +---------------------+--------------+-----------------+--------------+ | | | Wrap/Unwrap | ? | ? | ? | | | +---------------------+--------------+-----------------+--------------+ | | | Sign/Verify | ? | ? | ? | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | RSA | Generate key pair | Works | Works | Works | Works [4]_ [8]_ | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Encrypt/Decrypt | Works | Works | Works | Decrypt only [9]_ | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Wrap/Unwrap | Works | Works | Works | N/A | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Sign/Verify | Works | Works | Works | Works | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DSA | Generate parameters | Works | Error | N/A | N/A | | +---------------------+--------------+-----------------+ | | | | Generate key pair | Works | Caveats [5]_ | | | | +---------------------+--------------+-----------------+ | | | | Sign/Verify | Works | Works [4]_ | | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DH | Generate parameters | Works | N/A | N/A | N/A | | +---------------------+--------------+-----------------+ | | | | Generate key pair | Works | Caveats [6]_ | | | | +---------------------+--------------+-----------------+ | | | | Derive Key | Works | Caveats [7]_ | | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | EC | Generate key pair | Caveats [6]_ | ? [3]_ | N/A | Works | | +---------------------+--------------+-----------------+ +-------------------+ | | Sign/Verify (ECDSA) | Works [4]_ | ? [3]_ | | Sign only [9]_ | | +---------------------+--------------+-----------------+ +-------------------+ | | Derive key (ECDH) | Works | ? [3]_ | | ? | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | Proprietary extensions | N/A | Not implemented | N/A | N/A | +------------------------------+--------------+-----------------+--------------+-------------------+ .. [1] Device supports limited set of attributes. .. [2] Digesting keys is not supported. .. [3] Untested: requires support in device. .. [4] Default mechanism not supported, must specify a mechanism. .. [5] From existing domain parameters. .. [6] Local domain parameters only. .. [7] Generates security warnings about the derived key. .. [8] `store` parameter is ignored, all keys are stored. .. [9] Encryption/verify not supported, extract the public key Python version: * 3.4 (with `aenum`) * 3.5 (with `aenum`) * 3.6 PKCS#11 versions: * 2.11 * 2.20 * 2.40 Feel free to send pull requests for any functionality that's not exposed. The code is designed to be readable and expose the PKCS #11 spec in a straight-forward way. If you want your device supported, get in touch! More info on PKCS #11 --------------------- The latest version of the PKCS #11 spec is available from OASIS: http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html You should also consult the documentation for your PKCS #11 implementation. Many implementations expose additional vendor options configurable in your environment, including alternative features, modes and debugging information. License ------- MIT License Copyright (c) 2017 Danielle Madeley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Platform: UNKNOWN Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Security :: Cryptography python-pkcs11-0.7.0/python_pkcs11.egg-info/dependency_links.txt0000664000372000037200000000000113717606455025262 0ustar travistravis00000000000000 python-pkcs11-0.7.0/python_pkcs11.egg-info/top_level.txt0000664000372000037200000000000713717606455023743 0ustar travistravis00000000000000pkcs11 python-pkcs11-0.7.0/python_pkcs11.egg-info/SOURCES.txt0000664000372000037200000000235513717606456023106 0ustar travistravis00000000000000.gitignore .travis.yml README.rst dev-requirements.in dev-requirements.txt requirements.in requirements.txt setup.py docs/Makefile docs/api.rst docs/applied.rst docs/concurrency.rst docs/conf.py docs/index.rst docs/make.bat docs/opensc.rst extern/cryptoki.h extern/pkcs11.h extern/pkcs11f.h extern/pkcs11t.h pkcs11/__init__.py pkcs11/_errors.pyx pkcs11/_mswin.pxd pkcs11/_pkcs11.pyx pkcs11/_pkcs11_defn.pxd pkcs11/_utils.pyx pkcs11/constants.py pkcs11/defaults.py pkcs11/exceptions.py pkcs11/mechanisms.py pkcs11/types.py pkcs11/util/__init__.py pkcs11/util/dh.py pkcs11/util/dsa.py pkcs11/util/ec.py pkcs11/util/rsa.py pkcs11/util/x509.py python_pkcs11.egg-info/PKG-INFO python_pkcs11.egg-info/SOURCES.txt python_pkcs11.egg-info/dependency_links.txt python_pkcs11.egg-info/requires.txt python_pkcs11.egg-info/top_level.txt tests/__init__.py tests/test_aes.py tests/test_des.py tests/test_dh.py tests/test_digest.py tests/test_dsa.py tests/test_ecc.py tests/test_iterators.py tests/test_public_key_external.py tests/test_rsa.py tests/test_sessions.py tests/test_slots_and_tokens.py tests/test_threading.py tests/test_x509.py tools/buildbot/build.sh tools/buildbot/install.sh tools/buildbot/test.sh tools/nfast/build.sh tools/nfast/install.sh tools/nfast/test.shpython-pkcs11-0.7.0/python_pkcs11.egg-info/requires.txt0000664000372000037200000000007413717606455023615 0ustar travistravis00000000000000asn1crypto cached-property [:python_version < "3.6"] aenum python-pkcs11-0.7.0/.gitignore0000664000372000037200000000012113717606207016774 0ustar travistravis00000000000000*.so *.c __pycache__ /build /dist/ /docs/_build /python_pkcs11.egg-info/ /.eggs/python-pkcs11-0.7.0/extern/0000775000372000037200000000000013717606456016325 5ustar travistravis00000000000000python-pkcs11-0.7.0/extern/cryptoki.h0000664000372000037200000000432013717606207020333 0ustar travistravis00000000000000#ifndef _CRYPTOKI_H_ #define _CRYPTOKI_H_ 1 /* MIT License */ /* Copyright (c) 2019 Eric Devolder */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */ /* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE */ /* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION */ /* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION */ /* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef __cplusplus extern "C" { #endif #if defined(__CYGWIN64__) #pragma warning "Cygwin 64 bits build will only work with Cygwin64-compiled PKCS#11 modules" #endif #define CK_PTR * #define CK_DEFINE_FUNCTION(returnType, name) returnType name #define CK_DECLARE_FUNCTION(returnType, name) returnType name #define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name) #define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name) #ifndef NULL_PTR #define NULL_PTR 0 #endif #if defined(_MSC_VER) && defined(_WIN32) /* we are compiling using Visual C */ #pragma pack(push, cryptoki, 1) #elif defined(__CYGWIN__) #pragma pack(push, 1) #endif #include "pkcs11.h" #if defined(_MSC_VER) && defined(_WIN32) /* we are compiling using Visual C */ #pragma pack(pop, cryptoki) #elif defined(__CYGWIN__) #pragma pack(pop) #endif #ifdef __cplusplus } #endif #endif /* _CRYPTOKI_H_ */ python-pkcs11-0.7.0/extern/pkcs11.h0000664000372000037200000001750213717606207017577 0ustar travistravis00000000000000/* Copyright (c) OASIS Open 2016. All Rights Reserved./ * /Distributed under the terms of the OASIS IPR Policy, * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others. */ /* Latest version of the specification: * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html */ #ifndef _PKCS11_H_ #define _PKCS11_H_ 1 #ifdef __cplusplus extern "C" { #endif /* Before including this file (pkcs11.h) (or pkcs11t.h by * itself), 5 platform-specific macros must be defined. These * macros are described below, and typical definitions for them * are also given. Be advised that these definitions can depend * on both the platform and the compiler used (and possibly also * on whether a Cryptoki library is linked statically or * dynamically). * * In addition to defining these 5 macros, the packing convention * for Cryptoki structures should be set. The Cryptoki * convention on packing is that structures should be 1-byte * aligned. * * If you're using Microsoft Developer Studio 5.0 to produce * Win32 stuff, this might be done by using the following * preprocessor directive before including pkcs11.h or pkcs11t.h: * * #pragma pack(push, cryptoki, 1) * * and using the following preprocessor directive after including * pkcs11.h or pkcs11t.h: * * #pragma pack(pop, cryptoki) * * If you're using an earlier version of Microsoft Developer * Studio to produce Win16 stuff, this might be done by using * the following preprocessor directive before including * pkcs11.h or pkcs11t.h: * * #pragma pack(1) * * In a UNIX environment, you're on your own for this. You might * not need to do (or be able to do!) anything. * * * Now for the macros: * * * 1. CK_PTR: The indirection string for making a pointer to an * object. It can be used like this: * * typedef CK_BYTE CK_PTR CK_BYTE_PTR; * * If you're using Microsoft Developer Studio 5.0 to produce * Win32 stuff, it might be defined by: * * #define CK_PTR * * * If you're using an earlier version of Microsoft Developer * Studio to produce Win16 stuff, it might be defined by: * * #define CK_PTR far * * * In a typical UNIX environment, it might be defined by: * * #define CK_PTR * * * * 2. CK_DECLARE_FUNCTION(returnType, name): A macro which makes * an importable Cryptoki library function declaration out of a * return type and a function name. It should be used in the * following fashion: * * extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)( * CK_VOID_PTR pReserved * ); * * If you're using Microsoft Developer Studio 5.0 to declare a * function in a Win32 Cryptoki .dll, it might be defined by: * * #define CK_DECLARE_FUNCTION(returnType, name) \ * returnType __declspec(dllimport) name * * If you're using an earlier version of Microsoft Developer * Studio to declare a function in a Win16 Cryptoki .dll, it * might be defined by: * * #define CK_DECLARE_FUNCTION(returnType, name) \ * returnType __export _far _pascal name * * In a UNIX environment, it might be defined by: * * #define CK_DECLARE_FUNCTION(returnType, name) \ * returnType name * * * 3. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro * which makes a Cryptoki API function pointer declaration or * function pointer type declaration out of a return type and a * function name. It should be used in the following fashion: * * // Define funcPtr to be a pointer to a Cryptoki API function * // taking arguments args and returning CK_RV. * CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args); * * or * * // Define funcPtrType to be the type of a pointer to a * // Cryptoki API function taking arguments args and returning * // CK_RV, and then define funcPtr to be a variable of type * // funcPtrType. * typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args); * funcPtrType funcPtr; * * If you're using Microsoft Developer Studio 5.0 to access * functions in a Win32 Cryptoki .dll, in might be defined by: * * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ * returnType __declspec(dllimport) (* name) * * If you're using an earlier version of Microsoft Developer * Studio to access functions in a Win16 Cryptoki .dll, it might * be defined by: * * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ * returnType __export _far _pascal (* name) * * In a UNIX environment, it might be defined by: * * #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \ * returnType (* name) * * * 4. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes * a function pointer type for an application callback out of * a return type for the callback and a name for the callback. * It should be used in the following fashion: * * CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args); * * to declare a function pointer, myCallback, to a callback * which takes arguments args and returns a CK_RV. It can also * be used like this: * * typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args); * myCallbackType myCallback; * * If you're using Microsoft Developer Studio 5.0 to do Win32 * Cryptoki development, it might be defined by: * * #define CK_CALLBACK_FUNCTION(returnType, name) \ * returnType (* name) * * If you're using an earlier version of Microsoft Developer * Studio to do Win16 development, it might be defined by: * * #define CK_CALLBACK_FUNCTION(returnType, name) \ * returnType _far _pascal (* name) * * In a UNIX environment, it might be defined by: * * #define CK_CALLBACK_FUNCTION(returnType, name) \ * returnType (* name) * * * 5. NULL_PTR: This macro is the value of a NULL pointer. * * In any ANSI/ISO C environment (and in many others as well), * this should best be defined by * * #ifndef NULL_PTR * #define NULL_PTR 0 * #endif */ /* All the various Cryptoki types and #define'd values are in the * file pkcs11t.h. */ #include "pkcs11t.h" #define __PASTE(x,y) x##y /* ============================================================== * Define the "extern" form of all the entry points. * ============================================================== */ #define CK_NEED_ARG_LIST 1 #define CK_PKCS11_FUNCTION_INFO(name) \ extern CK_DECLARE_FUNCTION(CK_RV, name) /* pkcs11f.h has all the information about the Cryptoki * function prototypes. */ #include "pkcs11f.h" #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO /* ============================================================== * Define the typedef form of all the entry points. That is, for * each Cryptoki function C_XXX, define a type CK_C_XXX which is * a pointer to that kind of function. * ============================================================== */ #define CK_NEED_ARG_LIST 1 #define CK_PKCS11_FUNCTION_INFO(name) \ typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name)) /* pkcs11f.h has all the information about the Cryptoki * function prototypes. */ #include "pkcs11f.h" #undef CK_NEED_ARG_LIST #undef CK_PKCS11_FUNCTION_INFO /* ============================================================== * Define structed vector of entry points. A CK_FUNCTION_LIST * contains a CK_VERSION indicating a library's Cryptoki version * and then a whole slew of function pointers to the routines in * the library. This type was declared, but not defined, in * pkcs11t.h. * ============================================================== */ #define CK_PKCS11_FUNCTION_INFO(name) \ __PASTE(CK_,name) name; struct CK_FUNCTION_LIST { CK_VERSION version; /* Cryptoki version */ /* Pile all the function pointers into the CK_FUNCTION_LIST. */ /* pkcs11f.h has all the information about the Cryptoki * function prototypes. */ #include "pkcs11f.h" }; #undef CK_PKCS11_FUNCTION_INFO #undef __PASTE #ifdef __cplusplus } #endif #endif /* _PKCS11_H_ */ python-pkcs11-0.7.0/extern/pkcs11t.h0000664000372000037200000021511513717606207017763 0ustar travistravis00000000000000/* Copyright (c) OASIS Open 2016. All Rights Reserved./ * /Distributed under the terms of the OASIS IPR Policy, * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others. */ /* Latest version of the specification: * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html */ /* See top of pkcs11.h for information about the macros that * must be defined and the structure-packing conventions that * must be set before including this file. */ #ifndef _PKCS11T_H_ #define _PKCS11T_H_ 1 #define CRYPTOKI_VERSION_MAJOR 2 #define CRYPTOKI_VERSION_MINOR 40 #define CRYPTOKI_VERSION_AMENDMENT 0 #define CK_TRUE 1 #define CK_FALSE 0 #ifndef CK_DISABLE_TRUE_FALSE #ifndef FALSE #define FALSE CK_FALSE #endif #ifndef TRUE #define TRUE CK_TRUE #endif #endif /* an unsigned 8-bit value */ typedef unsigned char CK_BYTE; /* an unsigned 8-bit character */ typedef CK_BYTE CK_CHAR; /* an 8-bit UTF-8 character */ typedef CK_BYTE CK_UTF8CHAR; /* a BYTE-sized Boolean flag */ typedef CK_BYTE CK_BBOOL; /* an unsigned value, at least 32 bits long */ typedef unsigned long int CK_ULONG; /* a signed value, the same size as a CK_ULONG */ typedef long int CK_LONG; /* at least 32 bits; each bit is a Boolean flag */ typedef CK_ULONG CK_FLAGS; /* some special values for certain CK_ULONG variables */ #define CK_UNAVAILABLE_INFORMATION (~0UL) #define CK_EFFECTIVELY_INFINITE 0UL typedef CK_BYTE CK_PTR CK_BYTE_PTR; typedef CK_CHAR CK_PTR CK_CHAR_PTR; typedef CK_UTF8CHAR CK_PTR CK_UTF8CHAR_PTR; typedef CK_ULONG CK_PTR CK_ULONG_PTR; typedef void CK_PTR CK_VOID_PTR; /* Pointer to a CK_VOID_PTR-- i.e., pointer to pointer to void */ typedef CK_VOID_PTR CK_PTR CK_VOID_PTR_PTR; /* The following value is always invalid if used as a session * handle or object handle */ #define CK_INVALID_HANDLE 0UL typedef struct CK_VERSION { CK_BYTE major; /* integer portion of version number */ CK_BYTE minor; /* 1/100ths portion of version number */ } CK_VERSION; typedef CK_VERSION CK_PTR CK_VERSION_PTR; typedef struct CK_INFO { CK_VERSION cryptokiVersion; /* Cryptoki interface ver */ CK_UTF8CHAR manufacturerID[32]; /* blank padded */ CK_FLAGS flags; /* must be zero */ CK_UTF8CHAR libraryDescription[32]; /* blank padded */ CK_VERSION libraryVersion; /* version of library */ } CK_INFO; typedef CK_INFO CK_PTR CK_INFO_PTR; /* CK_NOTIFICATION enumerates the types of notifications that * Cryptoki provides to an application */ typedef CK_ULONG CK_NOTIFICATION; #define CKN_SURRENDER 0UL #define CKN_OTP_CHANGED 1UL typedef CK_ULONG CK_SLOT_ID; typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR; /* CK_SLOT_INFO provides information about a slot */ typedef struct CK_SLOT_INFO { CK_UTF8CHAR slotDescription[64]; /* blank padded */ CK_UTF8CHAR manufacturerID[32]; /* blank padded */ CK_FLAGS flags; CK_VERSION hardwareVersion; /* version of hardware */ CK_VERSION firmwareVersion; /* version of firmware */ } CK_SLOT_INFO; /* flags: bit flags that provide capabilities of the slot * Bit Flag Mask Meaning */ #define CKF_TOKEN_PRESENT 0x00000001UL /* a token is there */ #define CKF_REMOVABLE_DEVICE 0x00000002UL /* removable devices*/ #define CKF_HW_SLOT 0x00000004UL /* hardware slot */ typedef CK_SLOT_INFO CK_PTR CK_SLOT_INFO_PTR; /* CK_TOKEN_INFO provides information about a token */ typedef struct CK_TOKEN_INFO { CK_UTF8CHAR label[32]; /* blank padded */ CK_UTF8CHAR manufacturerID[32]; /* blank padded */ CK_UTF8CHAR model[16]; /* blank padded */ CK_CHAR serialNumber[16]; /* blank padded */ CK_FLAGS flags; /* see below */ CK_ULONG ulMaxSessionCount; /* max open sessions */ CK_ULONG ulSessionCount; /* sess. now open */ CK_ULONG ulMaxRwSessionCount; /* max R/W sessions */ CK_ULONG ulRwSessionCount; /* R/W sess. now open */ CK_ULONG ulMaxPinLen; /* in bytes */ CK_ULONG ulMinPinLen; /* in bytes */ CK_ULONG ulTotalPublicMemory; /* in bytes */ CK_ULONG ulFreePublicMemory; /* in bytes */ CK_ULONG ulTotalPrivateMemory; /* in bytes */ CK_ULONG ulFreePrivateMemory; /* in bytes */ CK_VERSION hardwareVersion; /* version of hardware */ CK_VERSION firmwareVersion; /* version of firmware */ CK_CHAR utcTime[16]; /* time */ } CK_TOKEN_INFO; /* The flags parameter is defined as follows: * Bit Flag Mask Meaning */ #define CKF_RNG 0x00000001UL /* has random # generator */ #define CKF_WRITE_PROTECTED 0x00000002UL /* token is write-protected */ #define CKF_LOGIN_REQUIRED 0x00000004UL /* user must login */ #define CKF_USER_PIN_INITIALIZED 0x00000008UL /* normal user's PIN is set */ /* CKF_RESTORE_KEY_NOT_NEEDED. If it is set, * that means that *every* time the state of cryptographic * operations of a session is successfully saved, all keys * needed to continue those operations are stored in the state */ #define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020UL /* CKF_CLOCK_ON_TOKEN. If it is set, that means * that the token has some sort of clock. The time on that * clock is returned in the token info structure */ #define CKF_CLOCK_ON_TOKEN 0x00000040UL /* CKF_PROTECTED_AUTHENTICATION_PATH. If it is * set, that means that there is some way for the user to login * without sending a PIN through the Cryptoki library itself */ #define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100UL /* CKF_DUAL_CRYPTO_OPERATIONS. If it is true, * that means that a single session with the token can perform * dual simultaneous cryptographic operations (digest and * encrypt; decrypt and digest; sign and encrypt; and decrypt * and sign) */ #define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200UL /* CKF_TOKEN_INITIALIZED. If it is true, the * token has been initialized using C_InitializeToken or an * equivalent mechanism outside the scope of PKCS #11. * Calling C_InitializeToken when this flag is set will cause * the token to be reinitialized. */ #define CKF_TOKEN_INITIALIZED 0x00000400UL /* CKF_SECONDARY_AUTHENTICATION. If it is * true, the token supports secondary authentication for * private key objects. */ #define CKF_SECONDARY_AUTHENTICATION 0x00000800UL /* CKF_USER_PIN_COUNT_LOW. If it is true, an * incorrect user login PIN has been entered at least once * since the last successful authentication. */ #define CKF_USER_PIN_COUNT_LOW 0x00010000UL /* CKF_USER_PIN_FINAL_TRY. If it is true, * supplying an incorrect user PIN will it to become locked. */ #define CKF_USER_PIN_FINAL_TRY 0x00020000UL /* CKF_USER_PIN_LOCKED. If it is true, the * user PIN has been locked. User login to the token is not * possible. */ #define CKF_USER_PIN_LOCKED 0x00040000UL /* CKF_USER_PIN_TO_BE_CHANGED. If it is true, * the user PIN value is the default value set by token * initialization or manufacturing, or the PIN has been * expired by the card. */ #define CKF_USER_PIN_TO_BE_CHANGED 0x00080000UL /* CKF_SO_PIN_COUNT_LOW. If it is true, an * incorrect SO login PIN has been entered at least once since * the last successful authentication. */ #define CKF_SO_PIN_COUNT_LOW 0x00100000UL /* CKF_SO_PIN_FINAL_TRY. If it is true, * supplying an incorrect SO PIN will it to become locked. */ #define CKF_SO_PIN_FINAL_TRY 0x00200000UL /* CKF_SO_PIN_LOCKED. If it is true, the SO * PIN has been locked. SO login to the token is not possible. */ #define CKF_SO_PIN_LOCKED 0x00400000UL /* CKF_SO_PIN_TO_BE_CHANGED. If it is true, * the SO PIN value is the default value set by token * initialization or manufacturing, or the PIN has been * expired by the card. */ #define CKF_SO_PIN_TO_BE_CHANGED 0x00800000UL #define CKF_ERROR_STATE 0x01000000UL typedef CK_TOKEN_INFO CK_PTR CK_TOKEN_INFO_PTR; /* CK_SESSION_HANDLE is a Cryptoki-assigned value that * identifies a session */ typedef CK_ULONG CK_SESSION_HANDLE; typedef CK_SESSION_HANDLE CK_PTR CK_SESSION_HANDLE_PTR; /* CK_USER_TYPE enumerates the types of Cryptoki users */ typedef CK_ULONG CK_USER_TYPE; /* Security Officer */ #define CKU_SO 0UL /* Normal user */ #define CKU_USER 1UL /* Context specific */ #define CKU_CONTEXT_SPECIFIC 2UL /* CK_STATE enumerates the session states */ typedef CK_ULONG CK_STATE; #define CKS_RO_PUBLIC_SESSION 0UL #define CKS_RO_USER_FUNCTIONS 1UL #define CKS_RW_PUBLIC_SESSION 2UL #define CKS_RW_USER_FUNCTIONS 3UL #define CKS_RW_SO_FUNCTIONS 4UL /* CK_SESSION_INFO provides information about a session */ typedef struct CK_SESSION_INFO { CK_SLOT_ID slotID; CK_STATE state; CK_FLAGS flags; /* see below */ CK_ULONG ulDeviceError; /* device-dependent error code */ } CK_SESSION_INFO; /* The flags are defined in the following table: * Bit Flag Mask Meaning */ #define CKF_RW_SESSION 0x00000002UL /* session is r/w */ #define CKF_SERIAL_SESSION 0x00000004UL /* no parallel */ typedef CK_SESSION_INFO CK_PTR CK_SESSION_INFO_PTR; /* CK_OBJECT_HANDLE is a token-specific identifier for an * object */ typedef CK_ULONG CK_OBJECT_HANDLE; typedef CK_OBJECT_HANDLE CK_PTR CK_OBJECT_HANDLE_PTR; /* CK_OBJECT_CLASS is a value that identifies the classes (or * types) of objects that Cryptoki recognizes. It is defined * as follows: */ typedef CK_ULONG CK_OBJECT_CLASS; /* The following classes of objects are defined: */ #define CKO_DATA 0x00000000UL #define CKO_CERTIFICATE 0x00000001UL #define CKO_PUBLIC_KEY 0x00000002UL #define CKO_PRIVATE_KEY 0x00000003UL #define CKO_SECRET_KEY 0x00000004UL #define CKO_HW_FEATURE 0x00000005UL #define CKO_DOMAIN_PARAMETERS 0x00000006UL #define CKO_MECHANISM 0x00000007UL #define CKO_OTP_KEY 0x00000008UL #define CKO_VENDOR_DEFINED 0x80000000UL typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR; /* CK_HW_FEATURE_TYPE is a value that identifies the hardware feature type * of an object with CK_OBJECT_CLASS equal to CKO_HW_FEATURE. */ typedef CK_ULONG CK_HW_FEATURE_TYPE; /* The following hardware feature types are defined */ #define CKH_MONOTONIC_COUNTER 0x00000001UL #define CKH_CLOCK 0x00000002UL #define CKH_USER_INTERFACE 0x00000003UL #define CKH_VENDOR_DEFINED 0x80000000UL /* CK_KEY_TYPE is a value that identifies a key type */ typedef CK_ULONG CK_KEY_TYPE; /* the following key types are defined: */ #define CKK_RSA 0x00000000UL #define CKK_DSA 0x00000001UL #define CKK_DH 0x00000002UL #define CKK_ECDSA 0x00000003UL /* Deprecated */ #define CKK_EC 0x00000003UL #define CKK_X9_42_DH 0x00000004UL #define CKK_KEA 0x00000005UL #define CKK_GENERIC_SECRET 0x00000010UL #define CKK_RC2 0x00000011UL #define CKK_RC4 0x00000012UL #define CKK_DES 0x00000013UL #define CKK_DES2 0x00000014UL #define CKK_DES3 0x00000015UL #define CKK_CAST 0x00000016UL #define CKK_CAST3 0x00000017UL #define CKK_CAST5 0x00000018UL /* Deprecated */ #define CKK_CAST128 0x00000018UL #define CKK_RC5 0x00000019UL #define CKK_IDEA 0x0000001AUL #define CKK_SKIPJACK 0x0000001BUL #define CKK_BATON 0x0000001CUL #define CKK_JUNIPER 0x0000001DUL #define CKK_CDMF 0x0000001EUL #define CKK_AES 0x0000001FUL #define CKK_BLOWFISH 0x00000020UL #define CKK_TWOFISH 0x00000021UL #define CKK_SECURID 0x00000022UL #define CKK_HOTP 0x00000023UL #define CKK_ACTI 0x00000024UL #define CKK_CAMELLIA 0x00000025UL #define CKK_ARIA 0x00000026UL #define CKK_MD5_HMAC 0x00000027UL #define CKK_SHA_1_HMAC 0x00000028UL #define CKK_RIPEMD128_HMAC 0x00000029UL #define CKK_RIPEMD160_HMAC 0x0000002AUL #define CKK_SHA256_HMAC 0x0000002BUL #define CKK_SHA384_HMAC 0x0000002CUL #define CKK_SHA512_HMAC 0x0000002DUL #define CKK_SHA224_HMAC 0x0000002EUL #define CKK_SEED 0x0000002FUL #define CKK_GOSTR3410 0x00000030UL #define CKK_GOSTR3411 0x00000031UL #define CKK_GOST28147 0x00000032UL /* from version 3.0 */ #define CKK_EC_EDWARDS 0x00000040UL #define CKK_VENDOR_DEFINED 0x80000000UL /* CK_CERTIFICATE_TYPE is a value that identifies a certificate * type */ typedef CK_ULONG CK_CERTIFICATE_TYPE; #define CK_CERTIFICATE_CATEGORY_UNSPECIFIED 0UL #define CK_CERTIFICATE_CATEGORY_TOKEN_USER 1UL #define CK_CERTIFICATE_CATEGORY_AUTHORITY 2UL #define CK_CERTIFICATE_CATEGORY_OTHER_ENTITY 3UL #define CK_SECURITY_DOMAIN_UNSPECIFIED 0UL #define CK_SECURITY_DOMAIN_MANUFACTURER 1UL #define CK_SECURITY_DOMAIN_OPERATOR 2UL #define CK_SECURITY_DOMAIN_THIRD_PARTY 3UL /* The following certificate types are defined: */ #define CKC_X_509 0x00000000UL #define CKC_X_509_ATTR_CERT 0x00000001UL #define CKC_WTLS 0x00000002UL #define CKC_VENDOR_DEFINED 0x80000000UL /* CK_ATTRIBUTE_TYPE is a value that identifies an attribute * type */ typedef CK_ULONG CK_ATTRIBUTE_TYPE; /* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which * consists of an array of values. */ #define CKF_ARRAY_ATTRIBUTE 0x40000000UL /* The following OTP-related defines relate to the CKA_OTP_FORMAT attribute */ #define CK_OTP_FORMAT_DECIMAL 0UL #define CK_OTP_FORMAT_HEXADECIMAL 1UL #define CK_OTP_FORMAT_ALPHANUMERIC 2UL #define CK_OTP_FORMAT_BINARY 3UL /* The following OTP-related defines relate to the CKA_OTP_..._REQUIREMENT * attributes */ #define CK_OTP_PARAM_IGNORED 0UL #define CK_OTP_PARAM_OPTIONAL 1UL #define CK_OTP_PARAM_MANDATORY 2UL /* The following attribute types are defined: */ #define CKA_CLASS 0x00000000UL #define CKA_TOKEN 0x00000001UL #define CKA_PRIVATE 0x00000002UL #define CKA_LABEL 0x00000003UL #define CKA_APPLICATION 0x00000010UL #define CKA_VALUE 0x00000011UL #define CKA_OBJECT_ID 0x00000012UL #define CKA_CERTIFICATE_TYPE 0x00000080UL #define CKA_ISSUER 0x00000081UL #define CKA_SERIAL_NUMBER 0x00000082UL #define CKA_AC_ISSUER 0x00000083UL #define CKA_OWNER 0x00000084UL #define CKA_ATTR_TYPES 0x00000085UL #define CKA_TRUSTED 0x00000086UL #define CKA_CERTIFICATE_CATEGORY 0x00000087UL #define CKA_JAVA_MIDP_SECURITY_DOMAIN 0x00000088UL #define CKA_URL 0x00000089UL #define CKA_HASH_OF_SUBJECT_PUBLIC_KEY 0x0000008AUL #define CKA_HASH_OF_ISSUER_PUBLIC_KEY 0x0000008BUL #define CKA_NAME_HASH_ALGORITHM 0x0000008CUL #define CKA_CHECK_VALUE 0x00000090UL #define CKA_KEY_TYPE 0x00000100UL #define CKA_SUBJECT 0x00000101UL #define CKA_ID 0x00000102UL #define CKA_SENSITIVE 0x00000103UL #define CKA_ENCRYPT 0x00000104UL #define CKA_DECRYPT 0x00000105UL #define CKA_WRAP 0x00000106UL #define CKA_UNWRAP 0x00000107UL #define CKA_SIGN 0x00000108UL #define CKA_SIGN_RECOVER 0x00000109UL #define CKA_VERIFY 0x0000010AUL #define CKA_VERIFY_RECOVER 0x0000010BUL #define CKA_DERIVE 0x0000010CUL #define CKA_START_DATE 0x00000110UL #define CKA_END_DATE 0x00000111UL #define CKA_MODULUS 0x00000120UL #define CKA_MODULUS_BITS 0x00000121UL #define CKA_PUBLIC_EXPONENT 0x00000122UL #define CKA_PRIVATE_EXPONENT 0x00000123UL #define CKA_PRIME_1 0x00000124UL #define CKA_PRIME_2 0x00000125UL #define CKA_EXPONENT_1 0x00000126UL #define CKA_EXPONENT_2 0x00000127UL #define CKA_COEFFICIENT 0x00000128UL #define CKA_PUBLIC_KEY_INFO 0x00000129UL #define CKA_PRIME 0x00000130UL #define CKA_SUBPRIME 0x00000131UL #define CKA_BASE 0x00000132UL #define CKA_PRIME_BITS 0x00000133UL #define CKA_SUBPRIME_BITS 0x00000134UL #define CKA_SUB_PRIME_BITS CKA_SUBPRIME_BITS #define CKA_VALUE_BITS 0x00000160UL #define CKA_VALUE_LEN 0x00000161UL #define CKA_EXTRACTABLE 0x00000162UL #define CKA_LOCAL 0x00000163UL #define CKA_NEVER_EXTRACTABLE 0x00000164UL #define CKA_ALWAYS_SENSITIVE 0x00000165UL #define CKA_KEY_GEN_MECHANISM 0x00000166UL #define CKA_MODIFIABLE 0x00000170UL #define CKA_COPYABLE 0x00000171UL #define CKA_DESTROYABLE 0x00000172UL #define CKA_ECDSA_PARAMS 0x00000180UL /* Deprecated */ #define CKA_EC_PARAMS 0x00000180UL #define CKA_EC_POINT 0x00000181UL #define CKA_SECONDARY_AUTH 0x00000200UL /* Deprecated */ #define CKA_AUTH_PIN_FLAGS 0x00000201UL /* Deprecated */ #define CKA_ALWAYS_AUTHENTICATE 0x00000202UL #define CKA_WRAP_WITH_TRUSTED 0x00000210UL #define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000211UL) #define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000212UL) #define CKA_DERIVE_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000213UL) #define CKA_OTP_FORMAT 0x00000220UL #define CKA_OTP_LENGTH 0x00000221UL #define CKA_OTP_TIME_INTERVAL 0x00000222UL #define CKA_OTP_USER_FRIENDLY_MODE 0x00000223UL #define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224UL #define CKA_OTP_TIME_REQUIREMENT 0x00000225UL #define CKA_OTP_COUNTER_REQUIREMENT 0x00000226UL #define CKA_OTP_PIN_REQUIREMENT 0x00000227UL #define CKA_OTP_COUNTER 0x0000022EUL #define CKA_OTP_TIME 0x0000022FUL #define CKA_OTP_USER_IDENTIFIER 0x0000022AUL #define CKA_OTP_SERVICE_IDENTIFIER 0x0000022BUL #define CKA_OTP_SERVICE_LOGO 0x0000022CUL #define CKA_OTP_SERVICE_LOGO_TYPE 0x0000022DUL #define CKA_GOSTR3410_PARAMS 0x00000250UL #define CKA_GOSTR3411_PARAMS 0x00000251UL #define CKA_GOST28147_PARAMS 0x00000252UL #define CKA_HW_FEATURE_TYPE 0x00000300UL #define CKA_RESET_ON_INIT 0x00000301UL #define CKA_HAS_RESET 0x00000302UL #define CKA_PIXEL_X 0x00000400UL #define CKA_PIXEL_Y 0x00000401UL #define CKA_RESOLUTION 0x00000402UL #define CKA_CHAR_ROWS 0x00000403UL #define CKA_CHAR_COLUMNS 0x00000404UL #define CKA_COLOR 0x00000405UL #define CKA_BITS_PER_PIXEL 0x00000406UL #define CKA_CHAR_SETS 0x00000480UL #define CKA_ENCODING_METHODS 0x00000481UL #define CKA_MIME_TYPES 0x00000482UL #define CKA_MECHANISM_TYPE 0x00000500UL #define CKA_REQUIRED_CMS_ATTRIBUTES 0x00000501UL #define CKA_DEFAULT_CMS_ATTRIBUTES 0x00000502UL #define CKA_SUPPORTED_CMS_ATTRIBUTES 0x00000503UL #define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE|0x00000600UL) #define CKA_VENDOR_DEFINED 0x80000000UL /* CK_ATTRIBUTE is a structure that includes the type, length * and value of an attribute */ typedef struct CK_ATTRIBUTE { CK_ATTRIBUTE_TYPE type; CK_VOID_PTR pValue; CK_ULONG ulValueLen; /* in bytes */ } CK_ATTRIBUTE; typedef CK_ATTRIBUTE CK_PTR CK_ATTRIBUTE_PTR; /* CK_DATE is a structure that defines a date */ typedef struct CK_DATE{ CK_CHAR year[4]; /* the year ("1900" - "9999") */ CK_CHAR month[2]; /* the month ("01" - "12") */ CK_CHAR day[2]; /* the day ("01" - "31") */ } CK_DATE; /* CK_MECHANISM_TYPE is a value that identifies a mechanism * type */ typedef CK_ULONG CK_MECHANISM_TYPE; /* the following mechanism types are defined: */ #define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000UL #define CKM_RSA_PKCS 0x00000001UL #define CKM_RSA_9796 0x00000002UL #define CKM_RSA_X_509 0x00000003UL #define CKM_MD2_RSA_PKCS 0x00000004UL #define CKM_MD5_RSA_PKCS 0x00000005UL #define CKM_SHA1_RSA_PKCS 0x00000006UL #define CKM_RIPEMD128_RSA_PKCS 0x00000007UL #define CKM_RIPEMD160_RSA_PKCS 0x00000008UL #define CKM_RSA_PKCS_OAEP 0x00000009UL #define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000AUL #define CKM_RSA_X9_31 0x0000000BUL #define CKM_SHA1_RSA_X9_31 0x0000000CUL #define CKM_RSA_PKCS_PSS 0x0000000DUL #define CKM_SHA1_RSA_PKCS_PSS 0x0000000EUL #define CKM_DSA_KEY_PAIR_GEN 0x00000010UL #define CKM_DSA 0x00000011UL #define CKM_DSA_SHA1 0x00000012UL #define CKM_DSA_SHA224 0x00000013UL #define CKM_DSA_SHA256 0x00000014UL #define CKM_DSA_SHA384 0x00000015UL #define CKM_DSA_SHA512 0x00000016UL #define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020UL #define CKM_DH_PKCS_DERIVE 0x00000021UL #define CKM_X9_42_DH_KEY_PAIR_GEN 0x00000030UL #define CKM_X9_42_DH_DERIVE 0x00000031UL #define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032UL #define CKM_X9_42_MQV_DERIVE 0x00000033UL #define CKM_SHA256_RSA_PKCS 0x00000040UL #define CKM_SHA384_RSA_PKCS 0x00000041UL #define CKM_SHA512_RSA_PKCS 0x00000042UL #define CKM_SHA256_RSA_PKCS_PSS 0x00000043UL #define CKM_SHA384_RSA_PKCS_PSS 0x00000044UL #define CKM_SHA512_RSA_PKCS_PSS 0x00000045UL #define CKM_SHA224_RSA_PKCS 0x00000046UL #define CKM_SHA224_RSA_PKCS_PSS 0x00000047UL #define CKM_SHA512_224 0x00000048UL #define CKM_SHA512_224_HMAC 0x00000049UL #define CKM_SHA512_224_HMAC_GENERAL 0x0000004AUL #define CKM_SHA512_224_KEY_DERIVATION 0x0000004BUL #define CKM_SHA512_256 0x0000004CUL #define CKM_SHA512_256_HMAC 0x0000004DUL #define CKM_SHA512_256_HMAC_GENERAL 0x0000004EUL #define CKM_SHA512_256_KEY_DERIVATION 0x0000004FUL #define CKM_SHA512_T 0x00000050UL #define CKM_SHA512_T_HMAC 0x00000051UL #define CKM_SHA512_T_HMAC_GENERAL 0x00000052UL #define CKM_SHA512_T_KEY_DERIVATION 0x00000053UL #define CKM_RC2_KEY_GEN 0x00000100UL #define CKM_RC2_ECB 0x00000101UL #define CKM_RC2_CBC 0x00000102UL #define CKM_RC2_MAC 0x00000103UL #define CKM_RC2_MAC_GENERAL 0x00000104UL #define CKM_RC2_CBC_PAD 0x00000105UL #define CKM_RC4_KEY_GEN 0x00000110UL #define CKM_RC4 0x00000111UL #define CKM_DES_KEY_GEN 0x00000120UL #define CKM_DES_ECB 0x00000121UL #define CKM_DES_CBC 0x00000122UL #define CKM_DES_MAC 0x00000123UL #define CKM_DES_MAC_GENERAL 0x00000124UL #define CKM_DES_CBC_PAD 0x00000125UL #define CKM_DES2_KEY_GEN 0x00000130UL #define CKM_DES3_KEY_GEN 0x00000131UL #define CKM_DES3_ECB 0x00000132UL #define CKM_DES3_CBC 0x00000133UL #define CKM_DES3_MAC 0x00000134UL #define CKM_DES3_MAC_GENERAL 0x00000135UL #define CKM_DES3_CBC_PAD 0x00000136UL #define CKM_DES3_CMAC_GENERAL 0x00000137UL #define CKM_DES3_CMAC 0x00000138UL #define CKM_CDMF_KEY_GEN 0x00000140UL #define CKM_CDMF_ECB 0x00000141UL #define CKM_CDMF_CBC 0x00000142UL #define CKM_CDMF_MAC 0x00000143UL #define CKM_CDMF_MAC_GENERAL 0x00000144UL #define CKM_CDMF_CBC_PAD 0x00000145UL #define CKM_DES_OFB64 0x00000150UL #define CKM_DES_OFB8 0x00000151UL #define CKM_DES_CFB64 0x00000152UL #define CKM_DES_CFB8 0x00000153UL #define CKM_MD2 0x00000200UL #define CKM_MD2_HMAC 0x00000201UL #define CKM_MD2_HMAC_GENERAL 0x00000202UL #define CKM_MD5 0x00000210UL #define CKM_MD5_HMAC 0x00000211UL #define CKM_MD5_HMAC_GENERAL 0x00000212UL #define CKM_SHA_1 0x00000220UL #define CKM_SHA_1_HMAC 0x00000221UL #define CKM_SHA_1_HMAC_GENERAL 0x00000222UL #define CKM_RIPEMD128 0x00000230UL #define CKM_RIPEMD128_HMAC 0x00000231UL #define CKM_RIPEMD128_HMAC_GENERAL 0x00000232UL #define CKM_RIPEMD160 0x00000240UL #define CKM_RIPEMD160_HMAC 0x00000241UL #define CKM_RIPEMD160_HMAC_GENERAL 0x00000242UL #define CKM_SHA256 0x00000250UL #define CKM_SHA256_HMAC 0x00000251UL #define CKM_SHA256_HMAC_GENERAL 0x00000252UL #define CKM_SHA224 0x00000255UL #define CKM_SHA224_HMAC 0x00000256UL #define CKM_SHA224_HMAC_GENERAL 0x00000257UL #define CKM_SHA384 0x00000260UL #define CKM_SHA384_HMAC 0x00000261UL #define CKM_SHA384_HMAC_GENERAL 0x00000262UL #define CKM_SHA512 0x00000270UL #define CKM_SHA512_HMAC 0x00000271UL #define CKM_SHA512_HMAC_GENERAL 0x00000272UL #define CKM_SECURID_KEY_GEN 0x00000280UL #define CKM_SECURID 0x00000282UL #define CKM_HOTP_KEY_GEN 0x00000290UL #define CKM_HOTP 0x00000291UL #define CKM_ACTI 0x000002A0UL #define CKM_ACTI_KEY_GEN 0x000002A1UL #define CKM_CAST_KEY_GEN 0x00000300UL #define CKM_CAST_ECB 0x00000301UL #define CKM_CAST_CBC 0x00000302UL #define CKM_CAST_MAC 0x00000303UL #define CKM_CAST_MAC_GENERAL 0x00000304UL #define CKM_CAST_CBC_PAD 0x00000305UL #define CKM_CAST3_KEY_GEN 0x00000310UL #define CKM_CAST3_ECB 0x00000311UL #define CKM_CAST3_CBC 0x00000312UL #define CKM_CAST3_MAC 0x00000313UL #define CKM_CAST3_MAC_GENERAL 0x00000314UL #define CKM_CAST3_CBC_PAD 0x00000315UL /* Note that CAST128 and CAST5 are the same algorithm */ #define CKM_CAST5_KEY_GEN 0x00000320UL #define CKM_CAST128_KEY_GEN 0x00000320UL #define CKM_CAST5_ECB 0x00000321UL #define CKM_CAST128_ECB 0x00000321UL #define CKM_CAST5_CBC 0x00000322UL /* Deprecated */ #define CKM_CAST128_CBC 0x00000322UL #define CKM_CAST5_MAC 0x00000323UL /* Deprecated */ #define CKM_CAST128_MAC 0x00000323UL #define CKM_CAST5_MAC_GENERAL 0x00000324UL /* Deprecated */ #define CKM_CAST128_MAC_GENERAL 0x00000324UL #define CKM_CAST5_CBC_PAD 0x00000325UL /* Deprecated */ #define CKM_CAST128_CBC_PAD 0x00000325UL #define CKM_RC5_KEY_GEN 0x00000330UL #define CKM_RC5_ECB 0x00000331UL #define CKM_RC5_CBC 0x00000332UL #define CKM_RC5_MAC 0x00000333UL #define CKM_RC5_MAC_GENERAL 0x00000334UL #define CKM_RC5_CBC_PAD 0x00000335UL #define CKM_IDEA_KEY_GEN 0x00000340UL #define CKM_IDEA_ECB 0x00000341UL #define CKM_IDEA_CBC 0x00000342UL #define CKM_IDEA_MAC 0x00000343UL #define CKM_IDEA_MAC_GENERAL 0x00000344UL #define CKM_IDEA_CBC_PAD 0x00000345UL #define CKM_GENERIC_SECRET_KEY_GEN 0x00000350UL #define CKM_CONCATENATE_BASE_AND_KEY 0x00000360UL #define CKM_CONCATENATE_BASE_AND_DATA 0x00000362UL #define CKM_CONCATENATE_DATA_AND_BASE 0x00000363UL #define CKM_XOR_BASE_AND_DATA 0x00000364UL #define CKM_EXTRACT_KEY_FROM_KEY 0x00000365UL #define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370UL #define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371UL #define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372UL #define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373UL #define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374UL #define CKM_TLS_MASTER_KEY_DERIVE 0x00000375UL #define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376UL #define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377UL #define CKM_TLS_PRF 0x00000378UL #define CKM_SSL3_MD5_MAC 0x00000380UL #define CKM_SSL3_SHA1_MAC 0x00000381UL #define CKM_MD5_KEY_DERIVATION 0x00000390UL #define CKM_MD2_KEY_DERIVATION 0x00000391UL #define CKM_SHA1_KEY_DERIVATION 0x00000392UL #define CKM_SHA256_KEY_DERIVATION 0x00000393UL #define CKM_SHA384_KEY_DERIVATION 0x00000394UL #define CKM_SHA512_KEY_DERIVATION 0x00000395UL #define CKM_SHA224_KEY_DERIVATION 0x00000396UL #define CKM_PBE_MD2_DES_CBC 0x000003A0UL #define CKM_PBE_MD5_DES_CBC 0x000003A1UL #define CKM_PBE_MD5_CAST_CBC 0x000003A2UL #define CKM_PBE_MD5_CAST3_CBC 0x000003A3UL #define CKM_PBE_MD5_CAST5_CBC 0x000003A4UL /* Deprecated */ #define CKM_PBE_MD5_CAST128_CBC 0x000003A4UL #define CKM_PBE_SHA1_CAST5_CBC 0x000003A5UL /* Deprecated */ #define CKM_PBE_SHA1_CAST128_CBC 0x000003A5UL #define CKM_PBE_SHA1_RC4_128 0x000003A6UL #define CKM_PBE_SHA1_RC4_40 0x000003A7UL #define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8UL #define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9UL #define CKM_PBE_SHA1_RC2_128_CBC 0x000003AAUL #define CKM_PBE_SHA1_RC2_40_CBC 0x000003ABUL #define CKM_PKCS5_PBKD2 0x000003B0UL #define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0UL #define CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0UL #define CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1UL #define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2UL #define CKM_WTLS_PRF 0x000003D3UL #define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4UL #define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5UL #define CKM_TLS10_MAC_SERVER 0x000003D6UL #define CKM_TLS10_MAC_CLIENT 0x000003D7UL #define CKM_TLS12_MAC 0x000003D8UL #define CKM_TLS12_KDF 0x000003D9UL #define CKM_TLS12_MASTER_KEY_DERIVE 0x000003E0UL #define CKM_TLS12_KEY_AND_MAC_DERIVE 0x000003E1UL #define CKM_TLS12_MASTER_KEY_DERIVE_DH 0x000003E2UL #define CKM_TLS12_KEY_SAFE_DERIVE 0x000003E3UL #define CKM_TLS_MAC 0x000003E4UL #define CKM_TLS_KDF 0x000003E5UL #define CKM_KEY_WRAP_LYNKS 0x00000400UL #define CKM_KEY_WRAP_SET_OAEP 0x00000401UL #define CKM_CMS_SIG 0x00000500UL #define CKM_KIP_DERIVE 0x00000510UL #define CKM_KIP_WRAP 0x00000511UL #define CKM_KIP_MAC 0x00000512UL #define CKM_CAMELLIA_KEY_GEN 0x00000550UL #define CKM_CAMELLIA_ECB 0x00000551UL #define CKM_CAMELLIA_CBC 0x00000552UL #define CKM_CAMELLIA_MAC 0x00000553UL #define CKM_CAMELLIA_MAC_GENERAL 0x00000554UL #define CKM_CAMELLIA_CBC_PAD 0x00000555UL #define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556UL #define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557UL #define CKM_CAMELLIA_CTR 0x00000558UL #define CKM_ARIA_KEY_GEN 0x00000560UL #define CKM_ARIA_ECB 0x00000561UL #define CKM_ARIA_CBC 0x00000562UL #define CKM_ARIA_MAC 0x00000563UL #define CKM_ARIA_MAC_GENERAL 0x00000564UL #define CKM_ARIA_CBC_PAD 0x00000565UL #define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566UL #define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567UL #define CKM_SEED_KEY_GEN 0x00000650UL #define CKM_SEED_ECB 0x00000651UL #define CKM_SEED_CBC 0x00000652UL #define CKM_SEED_MAC 0x00000653UL #define CKM_SEED_MAC_GENERAL 0x00000654UL #define CKM_SEED_CBC_PAD 0x00000655UL #define CKM_SEED_ECB_ENCRYPT_DATA 0x00000656UL #define CKM_SEED_CBC_ENCRYPT_DATA 0x00000657UL #define CKM_SKIPJACK_KEY_GEN 0x00001000UL #define CKM_SKIPJACK_ECB64 0x00001001UL #define CKM_SKIPJACK_CBC64 0x00001002UL #define CKM_SKIPJACK_OFB64 0x00001003UL #define CKM_SKIPJACK_CFB64 0x00001004UL #define CKM_SKIPJACK_CFB32 0x00001005UL #define CKM_SKIPJACK_CFB16 0x00001006UL #define CKM_SKIPJACK_CFB8 0x00001007UL #define CKM_SKIPJACK_WRAP 0x00001008UL #define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009UL #define CKM_SKIPJACK_RELAYX 0x0000100aUL #define CKM_KEA_KEY_PAIR_GEN 0x00001010UL #define CKM_KEA_KEY_DERIVE 0x00001011UL #define CKM_KEA_DERIVE 0x00001012UL #define CKM_FORTEZZA_TIMESTAMP 0x00001020UL #define CKM_BATON_KEY_GEN 0x00001030UL #define CKM_BATON_ECB128 0x00001031UL #define CKM_BATON_ECB96 0x00001032UL #define CKM_BATON_CBC128 0x00001033UL #define CKM_BATON_COUNTER 0x00001034UL #define CKM_BATON_SHUFFLE 0x00001035UL #define CKM_BATON_WRAP 0x00001036UL #define CKM_ECDSA_KEY_PAIR_GEN 0x00001040UL /* Deprecated */ #define CKM_EC_KEY_PAIR_GEN 0x00001040UL #define CKM_ECDSA 0x00001041UL #define CKM_ECDSA_SHA1 0x00001042UL #define CKM_ECDSA_SHA224 0x00001043UL #define CKM_ECDSA_SHA256 0x00001044UL #define CKM_ECDSA_SHA384 0x00001045UL #define CKM_ECDSA_SHA512 0x00001046UL #define CKM_ECDH1_DERIVE 0x00001050UL #define CKM_ECDH1_COFACTOR_DERIVE 0x00001051UL #define CKM_ECMQV_DERIVE 0x00001052UL #define CKM_ECDH_AES_KEY_WRAP 0x00001053UL #define CKM_RSA_AES_KEY_WRAP 0x00001054UL #define CKM_JUNIPER_KEY_GEN 0x00001060UL #define CKM_JUNIPER_ECB128 0x00001061UL #define CKM_JUNIPER_CBC128 0x00001062UL #define CKM_JUNIPER_COUNTER 0x00001063UL #define CKM_JUNIPER_SHUFFLE 0x00001064UL #define CKM_JUNIPER_WRAP 0x00001065UL #define CKM_FASTHASH 0x00001070UL #define CKM_AES_KEY_GEN 0x00001080UL #define CKM_AES_ECB 0x00001081UL #define CKM_AES_CBC 0x00001082UL #define CKM_AES_MAC 0x00001083UL #define CKM_AES_MAC_GENERAL 0x00001084UL #define CKM_AES_CBC_PAD 0x00001085UL #define CKM_AES_CTR 0x00001086UL #define CKM_AES_GCM 0x00001087UL #define CKM_AES_CCM 0x00001088UL #define CKM_AES_CTS 0x00001089UL #define CKM_AES_CMAC 0x0000108AUL #define CKM_AES_CMAC_GENERAL 0x0000108BUL #define CKM_AES_XCBC_MAC 0x0000108CUL #define CKM_AES_XCBC_MAC_96 0x0000108DUL #define CKM_AES_GMAC 0x0000108EUL #define CKM_BLOWFISH_KEY_GEN 0x00001090UL #define CKM_BLOWFISH_CBC 0x00001091UL #define CKM_TWOFISH_KEY_GEN 0x00001092UL #define CKM_TWOFISH_CBC 0x00001093UL #define CKM_BLOWFISH_CBC_PAD 0x00001094UL #define CKM_TWOFISH_CBC_PAD 0x00001095UL #define CKM_DES_ECB_ENCRYPT_DATA 0x00001100UL #define CKM_DES_CBC_ENCRYPT_DATA 0x00001101UL #define CKM_DES3_ECB_ENCRYPT_DATA 0x00001102UL #define CKM_DES3_CBC_ENCRYPT_DATA 0x00001103UL #define CKM_AES_ECB_ENCRYPT_DATA 0x00001104UL #define CKM_AES_CBC_ENCRYPT_DATA 0x00001105UL #define CKM_GOSTR3410_KEY_PAIR_GEN 0x00001200UL #define CKM_GOSTR3410 0x00001201UL #define CKM_GOSTR3410_WITH_GOSTR3411 0x00001202UL #define CKM_GOSTR3410_KEY_WRAP 0x00001203UL #define CKM_GOSTR3410_DERIVE 0x00001204UL #define CKM_GOSTR3411 0x00001210UL #define CKM_GOSTR3411_HMAC 0x00001211UL #define CKM_GOST28147_KEY_GEN 0x00001220UL #define CKM_GOST28147_ECB 0x00001221UL #define CKM_GOST28147 0x00001222UL #define CKM_GOST28147_MAC 0x00001223UL #define CKM_GOST28147_KEY_WRAP 0x00001224UL #define CKM_DSA_PARAMETER_GEN 0x00002000UL #define CKM_DH_PKCS_PARAMETER_GEN 0x00002001UL #define CKM_X9_42_DH_PARAMETER_GEN 0x00002002UL #define CKM_DSA_PROBABLISTIC_PARAMETER_GEN 0x00002003UL #define CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN 0x00002004UL #define CKM_AES_OFB 0x00002104UL #define CKM_AES_CFB64 0x00002105UL #define CKM_AES_CFB8 0x00002106UL #define CKM_AES_CFB128 0x00002107UL #define CKM_AES_CFB1 0x00002108UL #define CKM_AES_KEY_WRAP 0x00002109UL /* WAS: 0x00001090 */ #define CKM_AES_KEY_WRAP_PAD 0x0000210AUL /* WAS: 0x00001091 */ #define CKM_RSA_PKCS_TPM_1_1 0x00004001UL #define CKM_RSA_PKCS_OAEP_TPM_1_1 0x00004002UL /* from version 3.0 */ #define CKM_EC_EDWARDS_KEY_PAIR_GEN 0x00001055UL #define CKM_EDDSA 0x00001057UL #define CKM_VENDOR_DEFINED 0x80000000UL typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR; /* CK_MECHANISM is a structure that specifies a particular * mechanism */ typedef struct CK_MECHANISM { CK_MECHANISM_TYPE mechanism; CK_VOID_PTR pParameter; CK_ULONG ulParameterLen; /* in bytes */ } CK_MECHANISM; typedef CK_MECHANISM CK_PTR CK_MECHANISM_PTR; /* CK_MECHANISM_INFO provides information about a particular * mechanism */ typedef struct CK_MECHANISM_INFO { CK_ULONG ulMinKeySize; CK_ULONG ulMaxKeySize; CK_FLAGS flags; } CK_MECHANISM_INFO; /* The flags are defined as follows: * Bit Flag Mask Meaning */ #define CKF_HW 0x00000001UL /* performed by HW */ /* Specify whether or not a mechanism can be used for a particular task */ #define CKF_ENCRYPT 0x00000100UL #define CKF_DECRYPT 0x00000200UL #define CKF_DIGEST 0x00000400UL #define CKF_SIGN 0x00000800UL #define CKF_SIGN_RECOVER 0x00001000UL #define CKF_VERIFY 0x00002000UL #define CKF_VERIFY_RECOVER 0x00004000UL #define CKF_GENERATE 0x00008000UL #define CKF_GENERATE_KEY_PAIR 0x00010000UL #define CKF_WRAP 0x00020000UL #define CKF_UNWRAP 0x00040000UL #define CKF_DERIVE 0x00080000UL /* Describe a token's EC capabilities not available in mechanism * information. */ #define CKF_EC_F_P 0x00100000UL #define CKF_EC_F_2M 0x00200000UL #define CKF_EC_ECPARAMETERS 0x00400000UL #define CKF_EC_NAMEDCURVE 0x00800000UL #define CKF_EC_UNCOMPRESS 0x01000000UL #define CKF_EC_COMPRESS 0x02000000UL #define CKF_EXTENSION 0x80000000UL typedef CK_MECHANISM_INFO CK_PTR CK_MECHANISM_INFO_PTR; /* CK_RV is a value that identifies the return value of a * Cryptoki function */ typedef CK_ULONG CK_RV; #define CKR_OK 0x00000000UL #define CKR_CANCEL 0x00000001UL #define CKR_HOST_MEMORY 0x00000002UL #define CKR_SLOT_ID_INVALID 0x00000003UL #define CKR_GENERAL_ERROR 0x00000005UL #define CKR_FUNCTION_FAILED 0x00000006UL #define CKR_ARGUMENTS_BAD 0x00000007UL #define CKR_NO_EVENT 0x00000008UL #define CKR_NEED_TO_CREATE_THREADS 0x00000009UL #define CKR_CANT_LOCK 0x0000000AUL #define CKR_ATTRIBUTE_READ_ONLY 0x00000010UL #define CKR_ATTRIBUTE_SENSITIVE 0x00000011UL #define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012UL #define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013UL #define CKR_ACTION_PROHIBITED 0x0000001BUL #define CKR_DATA_INVALID 0x00000020UL #define CKR_DATA_LEN_RANGE 0x00000021UL #define CKR_DEVICE_ERROR 0x00000030UL #define CKR_DEVICE_MEMORY 0x00000031UL #define CKR_DEVICE_REMOVED 0x00000032UL #define CKR_ENCRYPTED_DATA_INVALID 0x00000040UL #define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041UL #define CKR_FUNCTION_CANCELED 0x00000050UL #define CKR_FUNCTION_NOT_PARALLEL 0x00000051UL #define CKR_FUNCTION_NOT_SUPPORTED 0x00000054UL #define CKR_KEY_HANDLE_INVALID 0x00000060UL #define CKR_KEY_SIZE_RANGE 0x00000062UL #define CKR_KEY_TYPE_INCONSISTENT 0x00000063UL #define CKR_KEY_NOT_NEEDED 0x00000064UL #define CKR_KEY_CHANGED 0x00000065UL #define CKR_KEY_NEEDED 0x00000066UL #define CKR_KEY_INDIGESTIBLE 0x00000067UL #define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068UL #define CKR_KEY_NOT_WRAPPABLE 0x00000069UL #define CKR_KEY_UNEXTRACTABLE 0x0000006AUL #define CKR_MECHANISM_INVALID 0x00000070UL #define CKR_MECHANISM_PARAM_INVALID 0x00000071UL #define CKR_OBJECT_HANDLE_INVALID 0x00000082UL #define CKR_OPERATION_ACTIVE 0x00000090UL #define CKR_OPERATION_NOT_INITIALIZED 0x00000091UL #define CKR_PIN_INCORRECT 0x000000A0UL #define CKR_PIN_INVALID 0x000000A1UL #define CKR_PIN_LEN_RANGE 0x000000A2UL #define CKR_PIN_EXPIRED 0x000000A3UL #define CKR_PIN_LOCKED 0x000000A4UL #define CKR_SESSION_CLOSED 0x000000B0UL #define CKR_SESSION_COUNT 0x000000B1UL #define CKR_SESSION_HANDLE_INVALID 0x000000B3UL #define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4UL #define CKR_SESSION_READ_ONLY 0x000000B5UL #define CKR_SESSION_EXISTS 0x000000B6UL #define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7UL #define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8UL #define CKR_SIGNATURE_INVALID 0x000000C0UL #define CKR_SIGNATURE_LEN_RANGE 0x000000C1UL #define CKR_TEMPLATE_INCOMPLETE 0x000000D0UL #define CKR_TEMPLATE_INCONSISTENT 0x000000D1UL #define CKR_TOKEN_NOT_PRESENT 0x000000E0UL #define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1UL #define CKR_TOKEN_WRITE_PROTECTED 0x000000E2UL #define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0UL #define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1UL #define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2UL #define CKR_USER_ALREADY_LOGGED_IN 0x00000100UL #define CKR_USER_NOT_LOGGED_IN 0x00000101UL #define CKR_USER_PIN_NOT_INITIALIZED 0x00000102UL #define CKR_USER_TYPE_INVALID 0x00000103UL #define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104UL #define CKR_USER_TOO_MANY_TYPES 0x00000105UL #define CKR_WRAPPED_KEY_INVALID 0x00000110UL #define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112UL #define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113UL #define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114UL #define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115UL #define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120UL #define CKR_RANDOM_NO_RNG 0x00000121UL #define CKR_DOMAIN_PARAMS_INVALID 0x00000130UL #define CKR_CURVE_NOT_SUPPORTED 0x00000140UL #define CKR_BUFFER_TOO_SMALL 0x00000150UL #define CKR_SAVED_STATE_INVALID 0x00000160UL #define CKR_INFORMATION_SENSITIVE 0x00000170UL #define CKR_STATE_UNSAVEABLE 0x00000180UL #define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190UL #define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191UL #define CKR_MUTEX_BAD 0x000001A0UL #define CKR_MUTEX_NOT_LOCKED 0x000001A1UL #define CKR_NEW_PIN_MODE 0x000001B0UL #define CKR_NEXT_OTP 0x000001B1UL #define CKR_EXCEEDED_MAX_ITERATIONS 0x000001B5UL #define CKR_FIPS_SELF_TEST_FAILED 0x000001B6UL #define CKR_LIBRARY_LOAD_FAILED 0x000001B7UL #define CKR_PIN_TOO_WEAK 0x000001B8UL #define CKR_PUBLIC_KEY_INVALID 0x000001B9UL #define CKR_FUNCTION_REJECTED 0x00000200UL #define CKR_VENDOR_DEFINED 0x80000000UL /* CK_NOTIFY is an application callback that processes events */ typedef CK_CALLBACK_FUNCTION(CK_RV, CK_NOTIFY)( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_NOTIFICATION event, CK_VOID_PTR pApplication /* passed to C_OpenSession */ ); /* CK_FUNCTION_LIST is a structure holding a Cryptoki spec * version and pointers of appropriate types to all the * Cryptoki functions */ typedef struct CK_FUNCTION_LIST CK_FUNCTION_LIST; typedef CK_FUNCTION_LIST CK_PTR CK_FUNCTION_LIST_PTR; typedef CK_FUNCTION_LIST_PTR CK_PTR CK_FUNCTION_LIST_PTR_PTR; /* CK_CREATEMUTEX is an application callback for creating a * mutex object */ typedef CK_CALLBACK_FUNCTION(CK_RV, CK_CREATEMUTEX)( CK_VOID_PTR_PTR ppMutex /* location to receive ptr to mutex */ ); /* CK_DESTROYMUTEX is an application callback for destroying a * mutex object */ typedef CK_CALLBACK_FUNCTION(CK_RV, CK_DESTROYMUTEX)( CK_VOID_PTR pMutex /* pointer to mutex */ ); /* CK_LOCKMUTEX is an application callback for locking a mutex */ typedef CK_CALLBACK_FUNCTION(CK_RV, CK_LOCKMUTEX)( CK_VOID_PTR pMutex /* pointer to mutex */ ); /* CK_UNLOCKMUTEX is an application callback for unlocking a * mutex */ typedef CK_CALLBACK_FUNCTION(CK_RV, CK_UNLOCKMUTEX)( CK_VOID_PTR pMutex /* pointer to mutex */ ); /* CK_C_INITIALIZE_ARGS provides the optional arguments to * C_Initialize */ typedef struct CK_C_INITIALIZE_ARGS { CK_CREATEMUTEX CreateMutex; CK_DESTROYMUTEX DestroyMutex; CK_LOCKMUTEX LockMutex; CK_UNLOCKMUTEX UnlockMutex; CK_FLAGS flags; CK_VOID_PTR pReserved; } CK_C_INITIALIZE_ARGS; /* flags: bit flags that provide capabilities of the slot * Bit Flag Mask Meaning */ #define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001UL #define CKF_OS_LOCKING_OK 0x00000002UL typedef CK_C_INITIALIZE_ARGS CK_PTR CK_C_INITIALIZE_ARGS_PTR; /* additional flags for parameters to functions */ /* CKF_DONT_BLOCK is for the function C_WaitForSlotEvent */ #define CKF_DONT_BLOCK 1 /* CK_RSA_PKCS_MGF_TYPE is used to indicate the Message * Generation Function (MGF) applied to a message block when * formatting a message block for the PKCS #1 OAEP encryption * scheme. */ typedef CK_ULONG CK_RSA_PKCS_MGF_TYPE; typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR; /* The following MGFs are defined */ #define CKG_MGF1_SHA1 0x00000001UL #define CKG_MGF1_SHA256 0x00000002UL #define CKG_MGF1_SHA384 0x00000003UL #define CKG_MGF1_SHA512 0x00000004UL #define CKG_MGF1_SHA224 0x00000005UL /* CK_RSA_PKCS_OAEP_SOURCE_TYPE is used to indicate the source * of the encoding parameter when formatting a message block * for the PKCS #1 OAEP encryption scheme. */ typedef CK_ULONG CK_RSA_PKCS_OAEP_SOURCE_TYPE; typedef CK_RSA_PKCS_OAEP_SOURCE_TYPE CK_PTR CK_RSA_PKCS_OAEP_SOURCE_TYPE_PTR; /* The following encoding parameter sources are defined */ #define CKZ_DATA_SPECIFIED 0x00000001UL /* CK_RSA_PKCS_OAEP_PARAMS provides the parameters to the * CKM_RSA_PKCS_OAEP mechanism. */ typedef struct CK_RSA_PKCS_OAEP_PARAMS { CK_MECHANISM_TYPE hashAlg; CK_RSA_PKCS_MGF_TYPE mgf; CK_RSA_PKCS_OAEP_SOURCE_TYPE source; CK_VOID_PTR pSourceData; CK_ULONG ulSourceDataLen; } CK_RSA_PKCS_OAEP_PARAMS; typedef CK_RSA_PKCS_OAEP_PARAMS CK_PTR CK_RSA_PKCS_OAEP_PARAMS_PTR; /* CK_RSA_PKCS_PSS_PARAMS provides the parameters to the * CKM_RSA_PKCS_PSS mechanism(s). */ typedef struct CK_RSA_PKCS_PSS_PARAMS { CK_MECHANISM_TYPE hashAlg; CK_RSA_PKCS_MGF_TYPE mgf; CK_ULONG sLen; } CK_RSA_PKCS_PSS_PARAMS; typedef CK_RSA_PKCS_PSS_PARAMS CK_PTR CK_RSA_PKCS_PSS_PARAMS_PTR; typedef CK_ULONG CK_EC_KDF_TYPE; /* The following EC Key Derivation Functions are defined */ #define CKD_NULL 0x00000001UL #define CKD_SHA1_KDF 0x00000002UL /* The following X9.42 DH key derivation functions are defined */ #define CKD_SHA1_KDF_ASN1 0x00000003UL #define CKD_SHA1_KDF_CONCATENATE 0x00000004UL #define CKD_SHA224_KDF 0x00000005UL #define CKD_SHA256_KDF 0x00000006UL #define CKD_SHA384_KDF 0x00000007UL #define CKD_SHA512_KDF 0x00000008UL #define CKD_CPDIVERSIFY_KDF 0x00000009UL /* CK_ECDH1_DERIVE_PARAMS provides the parameters to the * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms, * where each party contributes one key pair. */ typedef struct CK_ECDH1_DERIVE_PARAMS { CK_EC_KDF_TYPE kdf; CK_ULONG ulSharedDataLen; CK_BYTE_PTR pSharedData; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; } CK_ECDH1_DERIVE_PARAMS; typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR; /* * CK_ECDH2_DERIVE_PARAMS provides the parameters to the * CKM_ECMQV_DERIVE mechanism, where each party contributes two key pairs. */ typedef struct CK_ECDH2_DERIVE_PARAMS { CK_EC_KDF_TYPE kdf; CK_ULONG ulSharedDataLen; CK_BYTE_PTR pSharedData; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; CK_ULONG ulPrivateDataLen; CK_OBJECT_HANDLE hPrivateData; CK_ULONG ulPublicDataLen2; CK_BYTE_PTR pPublicData2; } CK_ECDH2_DERIVE_PARAMS; typedef CK_ECDH2_DERIVE_PARAMS CK_PTR CK_ECDH2_DERIVE_PARAMS_PTR; typedef struct CK_ECMQV_DERIVE_PARAMS { CK_EC_KDF_TYPE kdf; CK_ULONG ulSharedDataLen; CK_BYTE_PTR pSharedData; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; CK_ULONG ulPrivateDataLen; CK_OBJECT_HANDLE hPrivateData; CK_ULONG ulPublicDataLen2; CK_BYTE_PTR pPublicData2; CK_OBJECT_HANDLE publicKey; } CK_ECMQV_DERIVE_PARAMS; typedef CK_ECMQV_DERIVE_PARAMS CK_PTR CK_ECMQV_DERIVE_PARAMS_PTR; /* Typedefs and defines for the CKM_X9_42_DH_KEY_PAIR_GEN and the * CKM_X9_42_DH_PARAMETER_GEN mechanisms */ typedef CK_ULONG CK_X9_42_DH_KDF_TYPE; typedef CK_X9_42_DH_KDF_TYPE CK_PTR CK_X9_42_DH_KDF_TYPE_PTR; /* CK_X9_42_DH1_DERIVE_PARAMS provides the parameters to the * CKM_X9_42_DH_DERIVE key derivation mechanism, where each party * contributes one key pair */ typedef struct CK_X9_42_DH1_DERIVE_PARAMS { CK_X9_42_DH_KDF_TYPE kdf; CK_ULONG ulOtherInfoLen; CK_BYTE_PTR pOtherInfo; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; } CK_X9_42_DH1_DERIVE_PARAMS; typedef struct CK_X9_42_DH1_DERIVE_PARAMS CK_PTR CK_X9_42_DH1_DERIVE_PARAMS_PTR; /* CK_X9_42_DH2_DERIVE_PARAMS provides the parameters to the * CKM_X9_42_DH_HYBRID_DERIVE and CKM_X9_42_MQV_DERIVE key derivation * mechanisms, where each party contributes two key pairs */ typedef struct CK_X9_42_DH2_DERIVE_PARAMS { CK_X9_42_DH_KDF_TYPE kdf; CK_ULONG ulOtherInfoLen; CK_BYTE_PTR pOtherInfo; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; CK_ULONG ulPrivateDataLen; CK_OBJECT_HANDLE hPrivateData; CK_ULONG ulPublicDataLen2; CK_BYTE_PTR pPublicData2; } CK_X9_42_DH2_DERIVE_PARAMS; typedef CK_X9_42_DH2_DERIVE_PARAMS CK_PTR CK_X9_42_DH2_DERIVE_PARAMS_PTR; typedef struct CK_X9_42_MQV_DERIVE_PARAMS { CK_X9_42_DH_KDF_TYPE kdf; CK_ULONG ulOtherInfoLen; CK_BYTE_PTR pOtherInfo; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; CK_ULONG ulPrivateDataLen; CK_OBJECT_HANDLE hPrivateData; CK_ULONG ulPublicDataLen2; CK_BYTE_PTR pPublicData2; CK_OBJECT_HANDLE publicKey; } CK_X9_42_MQV_DERIVE_PARAMS; typedef CK_X9_42_MQV_DERIVE_PARAMS CK_PTR CK_X9_42_MQV_DERIVE_PARAMS_PTR; /* CK_KEA_DERIVE_PARAMS provides the parameters to the * CKM_KEA_DERIVE mechanism */ typedef struct CK_KEA_DERIVE_PARAMS { CK_BBOOL isSender; CK_ULONG ulRandomLen; CK_BYTE_PTR pRandomA; CK_BYTE_PTR pRandomB; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; } CK_KEA_DERIVE_PARAMS; typedef CK_KEA_DERIVE_PARAMS CK_PTR CK_KEA_DERIVE_PARAMS_PTR; /* CK_RC2_PARAMS provides the parameters to the CKM_RC2_ECB and * CKM_RC2_MAC mechanisms. An instance of CK_RC2_PARAMS just * holds the effective keysize */ typedef CK_ULONG CK_RC2_PARAMS; typedef CK_RC2_PARAMS CK_PTR CK_RC2_PARAMS_PTR; /* CK_RC2_CBC_PARAMS provides the parameters to the CKM_RC2_CBC * mechanism */ typedef struct CK_RC2_CBC_PARAMS { CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ CK_BYTE iv[8]; /* IV for CBC mode */ } CK_RC2_CBC_PARAMS; typedef CK_RC2_CBC_PARAMS CK_PTR CK_RC2_CBC_PARAMS_PTR; /* CK_RC2_MAC_GENERAL_PARAMS provides the parameters for the * CKM_RC2_MAC_GENERAL mechanism */ typedef struct CK_RC2_MAC_GENERAL_PARAMS { CK_ULONG ulEffectiveBits; /* effective bits (1-1024) */ CK_ULONG ulMacLength; /* Length of MAC in bytes */ } CK_RC2_MAC_GENERAL_PARAMS; typedef CK_RC2_MAC_GENERAL_PARAMS CK_PTR \ CK_RC2_MAC_GENERAL_PARAMS_PTR; /* CK_RC5_PARAMS provides the parameters to the CKM_RC5_ECB and * CKM_RC5_MAC mechanisms */ typedef struct CK_RC5_PARAMS { CK_ULONG ulWordsize; /* wordsize in bits */ CK_ULONG ulRounds; /* number of rounds */ } CK_RC5_PARAMS; typedef CK_RC5_PARAMS CK_PTR CK_RC5_PARAMS_PTR; /* CK_RC5_CBC_PARAMS provides the parameters to the CKM_RC5_CBC * mechanism */ typedef struct CK_RC5_CBC_PARAMS { CK_ULONG ulWordsize; /* wordsize in bits */ CK_ULONG ulRounds; /* number of rounds */ CK_BYTE_PTR pIv; /* pointer to IV */ CK_ULONG ulIvLen; /* length of IV in bytes */ } CK_RC5_CBC_PARAMS; typedef CK_RC5_CBC_PARAMS CK_PTR CK_RC5_CBC_PARAMS_PTR; /* CK_RC5_MAC_GENERAL_PARAMS provides the parameters for the * CKM_RC5_MAC_GENERAL mechanism */ typedef struct CK_RC5_MAC_GENERAL_PARAMS { CK_ULONG ulWordsize; /* wordsize in bits */ CK_ULONG ulRounds; /* number of rounds */ CK_ULONG ulMacLength; /* Length of MAC in bytes */ } CK_RC5_MAC_GENERAL_PARAMS; typedef CK_RC5_MAC_GENERAL_PARAMS CK_PTR \ CK_RC5_MAC_GENERAL_PARAMS_PTR; /* CK_MAC_GENERAL_PARAMS provides the parameters to most block * ciphers' MAC_GENERAL mechanisms. Its value is the length of * the MAC */ typedef CK_ULONG CK_MAC_GENERAL_PARAMS; typedef CK_MAC_GENERAL_PARAMS CK_PTR CK_MAC_GENERAL_PARAMS_PTR; typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS { CK_BYTE iv[8]; CK_BYTE_PTR pData; CK_ULONG length; } CK_DES_CBC_ENCRYPT_DATA_PARAMS; typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS { CK_BYTE iv[16]; CK_BYTE_PTR pData; CK_ULONG length; } CK_AES_CBC_ENCRYPT_DATA_PARAMS; typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR; /* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the * CKM_SKIPJACK_PRIVATE_WRAP mechanism */ typedef struct CK_SKIPJACK_PRIVATE_WRAP_PARAMS { CK_ULONG ulPasswordLen; CK_BYTE_PTR pPassword; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pPublicData; CK_ULONG ulPAndGLen; CK_ULONG ulQLen; CK_ULONG ulRandomLen; CK_BYTE_PTR pRandomA; CK_BYTE_PTR pPrimeP; CK_BYTE_PTR pBaseG; CK_BYTE_PTR pSubprimeQ; } CK_SKIPJACK_PRIVATE_WRAP_PARAMS; typedef CK_SKIPJACK_PRIVATE_WRAP_PARAMS CK_PTR \ CK_SKIPJACK_PRIVATE_WRAP_PARAMS_PTR; /* CK_SKIPJACK_RELAYX_PARAMS provides the parameters to the * CKM_SKIPJACK_RELAYX mechanism */ typedef struct CK_SKIPJACK_RELAYX_PARAMS { CK_ULONG ulOldWrappedXLen; CK_BYTE_PTR pOldWrappedX; CK_ULONG ulOldPasswordLen; CK_BYTE_PTR pOldPassword; CK_ULONG ulOldPublicDataLen; CK_BYTE_PTR pOldPublicData; CK_ULONG ulOldRandomLen; CK_BYTE_PTR pOldRandomA; CK_ULONG ulNewPasswordLen; CK_BYTE_PTR pNewPassword; CK_ULONG ulNewPublicDataLen; CK_BYTE_PTR pNewPublicData; CK_ULONG ulNewRandomLen; CK_BYTE_PTR pNewRandomA; } CK_SKIPJACK_RELAYX_PARAMS; typedef CK_SKIPJACK_RELAYX_PARAMS CK_PTR \ CK_SKIPJACK_RELAYX_PARAMS_PTR; typedef struct CK_PBE_PARAMS { CK_BYTE_PTR pInitVector; CK_UTF8CHAR_PTR pPassword; CK_ULONG ulPasswordLen; CK_BYTE_PTR pSalt; CK_ULONG ulSaltLen; CK_ULONG ulIteration; } CK_PBE_PARAMS; typedef CK_PBE_PARAMS CK_PTR CK_PBE_PARAMS_PTR; /* CK_KEY_WRAP_SET_OAEP_PARAMS provides the parameters to the * CKM_KEY_WRAP_SET_OAEP mechanism */ typedef struct CK_KEY_WRAP_SET_OAEP_PARAMS { CK_BYTE bBC; /* block contents byte */ CK_BYTE_PTR pX; /* extra data */ CK_ULONG ulXLen; /* length of extra data in bytes */ } CK_KEY_WRAP_SET_OAEP_PARAMS; typedef CK_KEY_WRAP_SET_OAEP_PARAMS CK_PTR CK_KEY_WRAP_SET_OAEP_PARAMS_PTR; typedef struct CK_SSL3_RANDOM_DATA { CK_BYTE_PTR pClientRandom; CK_ULONG ulClientRandomLen; CK_BYTE_PTR pServerRandom; CK_ULONG ulServerRandomLen; } CK_SSL3_RANDOM_DATA; typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS { CK_SSL3_RANDOM_DATA RandomInfo; CK_VERSION_PTR pVersion; } CK_SSL3_MASTER_KEY_DERIVE_PARAMS; typedef struct CK_SSL3_MASTER_KEY_DERIVE_PARAMS CK_PTR \ CK_SSL3_MASTER_KEY_DERIVE_PARAMS_PTR; typedef struct CK_SSL3_KEY_MAT_OUT { CK_OBJECT_HANDLE hClientMacSecret; CK_OBJECT_HANDLE hServerMacSecret; CK_OBJECT_HANDLE hClientKey; CK_OBJECT_HANDLE hServerKey; CK_BYTE_PTR pIVClient; CK_BYTE_PTR pIVServer; } CK_SSL3_KEY_MAT_OUT; typedef CK_SSL3_KEY_MAT_OUT CK_PTR CK_SSL3_KEY_MAT_OUT_PTR; typedef struct CK_SSL3_KEY_MAT_PARAMS { CK_ULONG ulMacSizeInBits; CK_ULONG ulKeySizeInBits; CK_ULONG ulIVSizeInBits; CK_BBOOL bIsExport; CK_SSL3_RANDOM_DATA RandomInfo; CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial; } CK_SSL3_KEY_MAT_PARAMS; typedef CK_SSL3_KEY_MAT_PARAMS CK_PTR CK_SSL3_KEY_MAT_PARAMS_PTR; typedef struct CK_TLS_PRF_PARAMS { CK_BYTE_PTR pSeed; CK_ULONG ulSeedLen; CK_BYTE_PTR pLabel; CK_ULONG ulLabelLen; CK_BYTE_PTR pOutput; CK_ULONG_PTR pulOutputLen; } CK_TLS_PRF_PARAMS; typedef CK_TLS_PRF_PARAMS CK_PTR CK_TLS_PRF_PARAMS_PTR; typedef struct CK_WTLS_RANDOM_DATA { CK_BYTE_PTR pClientRandom; CK_ULONG ulClientRandomLen; CK_BYTE_PTR pServerRandom; CK_ULONG ulServerRandomLen; } CK_WTLS_RANDOM_DATA; typedef CK_WTLS_RANDOM_DATA CK_PTR CK_WTLS_RANDOM_DATA_PTR; typedef struct CK_WTLS_MASTER_KEY_DERIVE_PARAMS { CK_MECHANISM_TYPE DigestMechanism; CK_WTLS_RANDOM_DATA RandomInfo; CK_BYTE_PTR pVersion; } CK_WTLS_MASTER_KEY_DERIVE_PARAMS; typedef CK_WTLS_MASTER_KEY_DERIVE_PARAMS CK_PTR \ CK_WTLS_MASTER_KEY_DERIVE_PARAMS_PTR; typedef struct CK_WTLS_PRF_PARAMS { CK_MECHANISM_TYPE DigestMechanism; CK_BYTE_PTR pSeed; CK_ULONG ulSeedLen; CK_BYTE_PTR pLabel; CK_ULONG ulLabelLen; CK_BYTE_PTR pOutput; CK_ULONG_PTR pulOutputLen; } CK_WTLS_PRF_PARAMS; typedef CK_WTLS_PRF_PARAMS CK_PTR CK_WTLS_PRF_PARAMS_PTR; typedef struct CK_WTLS_KEY_MAT_OUT { CK_OBJECT_HANDLE hMacSecret; CK_OBJECT_HANDLE hKey; CK_BYTE_PTR pIV; } CK_WTLS_KEY_MAT_OUT; typedef CK_WTLS_KEY_MAT_OUT CK_PTR CK_WTLS_KEY_MAT_OUT_PTR; typedef struct CK_WTLS_KEY_MAT_PARAMS { CK_MECHANISM_TYPE DigestMechanism; CK_ULONG ulMacSizeInBits; CK_ULONG ulKeySizeInBits; CK_ULONG ulIVSizeInBits; CK_ULONG ulSequenceNumber; CK_BBOOL bIsExport; CK_WTLS_RANDOM_DATA RandomInfo; CK_WTLS_KEY_MAT_OUT_PTR pReturnedKeyMaterial; } CK_WTLS_KEY_MAT_PARAMS; typedef CK_WTLS_KEY_MAT_PARAMS CK_PTR CK_WTLS_KEY_MAT_PARAMS_PTR; typedef struct CK_CMS_SIG_PARAMS { CK_OBJECT_HANDLE certificateHandle; CK_MECHANISM_PTR pSigningMechanism; CK_MECHANISM_PTR pDigestMechanism; CK_UTF8CHAR_PTR pContentType; CK_BYTE_PTR pRequestedAttributes; CK_ULONG ulRequestedAttributesLen; CK_BYTE_PTR pRequiredAttributes; CK_ULONG ulRequiredAttributesLen; } CK_CMS_SIG_PARAMS; typedef CK_CMS_SIG_PARAMS CK_PTR CK_CMS_SIG_PARAMS_PTR; typedef struct CK_KEY_DERIVATION_STRING_DATA { CK_BYTE_PTR pData; CK_ULONG ulLen; } CK_KEY_DERIVATION_STRING_DATA; typedef CK_KEY_DERIVATION_STRING_DATA CK_PTR \ CK_KEY_DERIVATION_STRING_DATA_PTR; /* The CK_EXTRACT_PARAMS is used for the * CKM_EXTRACT_KEY_FROM_KEY mechanism. It specifies which bit * of the base key should be used as the first bit of the * derived key */ typedef CK_ULONG CK_EXTRACT_PARAMS; typedef CK_EXTRACT_PARAMS CK_PTR CK_EXTRACT_PARAMS_PTR; /* CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE is used to * indicate the Pseudo-Random Function (PRF) used to generate * key bits using PKCS #5 PBKDF2. */ typedef CK_ULONG CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE; typedef CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE CK_PTR \ CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE_PTR; #define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001UL #define CKP_PKCS5_PBKD2_HMAC_GOSTR3411 0x00000002UL #define CKP_PKCS5_PBKD2_HMAC_SHA224 0x00000003UL #define CKP_PKCS5_PBKD2_HMAC_SHA256 0x00000004UL #define CKP_PKCS5_PBKD2_HMAC_SHA384 0x00000005UL #define CKP_PKCS5_PBKD2_HMAC_SHA512 0x00000006UL #define CKP_PKCS5_PBKD2_HMAC_SHA512_224 0x00000007UL #define CKP_PKCS5_PBKD2_HMAC_SHA512_256 0x00000008UL /* CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE is used to indicate the * source of the salt value when deriving a key using PKCS #5 * PBKDF2. */ typedef CK_ULONG CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE; typedef CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE CK_PTR \ CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE_PTR; /* The following salt value sources are defined in PKCS #5 v2.0. */ #define CKZ_SALT_SPECIFIED 0x00000001UL /* CK_PKCS5_PBKD2_PARAMS is a structure that provides the * parameters to the CKM_PKCS5_PBKD2 mechanism. */ typedef struct CK_PKCS5_PBKD2_PARAMS { CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; CK_VOID_PTR pSaltSourceData; CK_ULONG ulSaltSourceDataLen; CK_ULONG iterations; CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; CK_VOID_PTR pPrfData; CK_ULONG ulPrfDataLen; CK_UTF8CHAR_PTR pPassword; CK_ULONG_PTR ulPasswordLen; } CK_PKCS5_PBKD2_PARAMS; typedef CK_PKCS5_PBKD2_PARAMS CK_PTR CK_PKCS5_PBKD2_PARAMS_PTR; /* CK_PKCS5_PBKD2_PARAMS2 is a corrected version of the CK_PKCS5_PBKD2_PARAMS * structure that provides the parameters to the CKM_PKCS5_PBKD2 mechanism * noting that the ulPasswordLen field is a CK_ULONG and not a CK_ULONG_PTR. */ typedef struct CK_PKCS5_PBKD2_PARAMS2 { CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource; CK_VOID_PTR pSaltSourceData; CK_ULONG ulSaltSourceDataLen; CK_ULONG iterations; CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf; CK_VOID_PTR pPrfData; CK_ULONG ulPrfDataLen; CK_UTF8CHAR_PTR pPassword; CK_ULONG ulPasswordLen; } CK_PKCS5_PBKD2_PARAMS2; typedef CK_PKCS5_PBKD2_PARAMS2 CK_PTR CK_PKCS5_PBKD2_PARAMS2_PTR; typedef CK_ULONG CK_OTP_PARAM_TYPE; typedef CK_OTP_PARAM_TYPE CK_PARAM_TYPE; /* backward compatibility */ typedef struct CK_OTP_PARAM { CK_OTP_PARAM_TYPE type; CK_VOID_PTR pValue; CK_ULONG ulValueLen; } CK_OTP_PARAM; typedef CK_OTP_PARAM CK_PTR CK_OTP_PARAM_PTR; typedef struct CK_OTP_PARAMS { CK_OTP_PARAM_PTR pParams; CK_ULONG ulCount; } CK_OTP_PARAMS; typedef CK_OTP_PARAMS CK_PTR CK_OTP_PARAMS_PTR; typedef struct CK_OTP_SIGNATURE_INFO { CK_OTP_PARAM_PTR pParams; CK_ULONG ulCount; } CK_OTP_SIGNATURE_INFO; typedef CK_OTP_SIGNATURE_INFO CK_PTR CK_OTP_SIGNATURE_INFO_PTR; #define CK_OTP_VALUE 0UL #define CK_OTP_PIN 1UL #define CK_OTP_CHALLENGE 2UL #define CK_OTP_TIME 3UL #define CK_OTP_COUNTER 4UL #define CK_OTP_FLAGS 5UL #define CK_OTP_OUTPUT_LENGTH 6UL #define CK_OTP_OUTPUT_FORMAT 7UL #define CKF_NEXT_OTP 0x00000001UL #define CKF_EXCLUDE_TIME 0x00000002UL #define CKF_EXCLUDE_COUNTER 0x00000004UL #define CKF_EXCLUDE_CHALLENGE 0x00000008UL #define CKF_EXCLUDE_PIN 0x00000010UL #define CKF_USER_FRIENDLY_OTP 0x00000020UL typedef struct CK_KIP_PARAMS { CK_MECHANISM_PTR pMechanism; CK_OBJECT_HANDLE hKey; CK_BYTE_PTR pSeed; CK_ULONG ulSeedLen; } CK_KIP_PARAMS; typedef CK_KIP_PARAMS CK_PTR CK_KIP_PARAMS_PTR; typedef struct CK_AES_CTR_PARAMS { CK_ULONG ulCounterBits; CK_BYTE cb[16]; } CK_AES_CTR_PARAMS; typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR; typedef struct CK_GCM_PARAMS { CK_BYTE_PTR pIv; CK_ULONG ulIvLen; CK_ULONG ulIvBits; CK_BYTE_PTR pAAD; CK_ULONG ulAADLen; CK_ULONG ulTagBits; } CK_GCM_PARAMS; typedef CK_GCM_PARAMS CK_PTR CK_GCM_PARAMS_PTR; typedef struct CK_CCM_PARAMS { CK_ULONG ulDataLen; CK_BYTE_PTR pNonce; CK_ULONG ulNonceLen; CK_BYTE_PTR pAAD; CK_ULONG ulAADLen; CK_ULONG ulMACLen; } CK_CCM_PARAMS; typedef CK_CCM_PARAMS CK_PTR CK_CCM_PARAMS_PTR; /* Deprecated. Use CK_GCM_PARAMS */ typedef struct CK_AES_GCM_PARAMS { CK_BYTE_PTR pIv; CK_ULONG ulIvLen; CK_ULONG ulIvBits; CK_BYTE_PTR pAAD; CK_ULONG ulAADLen; CK_ULONG ulTagBits; } CK_AES_GCM_PARAMS; typedef CK_AES_GCM_PARAMS CK_PTR CK_AES_GCM_PARAMS_PTR; /* Deprecated. Use CK_CCM_PARAMS */ typedef struct CK_AES_CCM_PARAMS { CK_ULONG ulDataLen; CK_BYTE_PTR pNonce; CK_ULONG ulNonceLen; CK_BYTE_PTR pAAD; CK_ULONG ulAADLen; CK_ULONG ulMACLen; } CK_AES_CCM_PARAMS; typedef CK_AES_CCM_PARAMS CK_PTR CK_AES_CCM_PARAMS_PTR; typedef struct CK_CAMELLIA_CTR_PARAMS { CK_ULONG ulCounterBits; CK_BYTE cb[16]; } CK_CAMELLIA_CTR_PARAMS; typedef CK_CAMELLIA_CTR_PARAMS CK_PTR CK_CAMELLIA_CTR_PARAMS_PTR; typedef struct CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS { CK_BYTE iv[16]; CK_BYTE_PTR pData; CK_ULONG length; } CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS; typedef CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR \ CK_CAMELLIA_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct CK_ARIA_CBC_ENCRYPT_DATA_PARAMS { CK_BYTE iv[16]; CK_BYTE_PTR pData; CK_ULONG length; } CK_ARIA_CBC_ENCRYPT_DATA_PARAMS; typedef CK_ARIA_CBC_ENCRYPT_DATA_PARAMS CK_PTR \ CK_ARIA_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct CK_DSA_PARAMETER_GEN_PARAM { CK_MECHANISM_TYPE hash; CK_BYTE_PTR pSeed; CK_ULONG ulSeedLen; CK_ULONG ulIndex; } CK_DSA_PARAMETER_GEN_PARAM; typedef CK_DSA_PARAMETER_GEN_PARAM CK_PTR CK_DSA_PARAMETER_GEN_PARAM_PTR; typedef struct CK_ECDH_AES_KEY_WRAP_PARAMS { CK_ULONG ulAESKeyBits; CK_EC_KDF_TYPE kdf; CK_ULONG ulSharedDataLen; CK_BYTE_PTR pSharedData; } CK_ECDH_AES_KEY_WRAP_PARAMS; typedef CK_ECDH_AES_KEY_WRAP_PARAMS CK_PTR CK_ECDH_AES_KEY_WRAP_PARAMS_PTR; typedef CK_ULONG CK_JAVA_MIDP_SECURITY_DOMAIN; typedef CK_ULONG CK_CERTIFICATE_CATEGORY; typedef struct CK_RSA_AES_KEY_WRAP_PARAMS { CK_ULONG ulAESKeyBits; CK_RSA_PKCS_OAEP_PARAMS_PTR pOAEPParams; } CK_RSA_AES_KEY_WRAP_PARAMS; typedef CK_RSA_AES_KEY_WRAP_PARAMS CK_PTR CK_RSA_AES_KEY_WRAP_PARAMS_PTR; typedef struct CK_TLS12_MASTER_KEY_DERIVE_PARAMS { CK_SSL3_RANDOM_DATA RandomInfo; CK_VERSION_PTR pVersion; CK_MECHANISM_TYPE prfHashMechanism; } CK_TLS12_MASTER_KEY_DERIVE_PARAMS; typedef CK_TLS12_MASTER_KEY_DERIVE_PARAMS CK_PTR \ CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR; typedef struct CK_TLS12_KEY_MAT_PARAMS { CK_ULONG ulMacSizeInBits; CK_ULONG ulKeySizeInBits; CK_ULONG ulIVSizeInBits; CK_BBOOL bIsExport; CK_SSL3_RANDOM_DATA RandomInfo; CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial; CK_MECHANISM_TYPE prfHashMechanism; } CK_TLS12_KEY_MAT_PARAMS; typedef CK_TLS12_KEY_MAT_PARAMS CK_PTR CK_TLS12_KEY_MAT_PARAMS_PTR; typedef struct CK_TLS_KDF_PARAMS { CK_MECHANISM_TYPE prfMechanism; CK_BYTE_PTR pLabel; CK_ULONG ulLabelLength; CK_SSL3_RANDOM_DATA RandomInfo; CK_BYTE_PTR pContextData; CK_ULONG ulContextDataLength; } CK_TLS_KDF_PARAMS; typedef CK_TLS_KDF_PARAMS CK_PTR CK_TLS_KDF_PARAMS_PTR; typedef struct CK_TLS_MAC_PARAMS { CK_MECHANISM_TYPE prfHashMechanism; CK_ULONG ulMacLength; CK_ULONG ulServerOrClient; } CK_TLS_MAC_PARAMS; typedef CK_TLS_MAC_PARAMS CK_PTR CK_TLS_MAC_PARAMS_PTR; typedef struct CK_GOSTR3410_DERIVE_PARAMS { CK_EC_KDF_TYPE kdf; CK_BYTE_PTR pPublicData; CK_ULONG ulPublicDataLen; CK_BYTE_PTR pUKM; CK_ULONG ulUKMLen; } CK_GOSTR3410_DERIVE_PARAMS; typedef CK_GOSTR3410_DERIVE_PARAMS CK_PTR CK_GOSTR3410_DERIVE_PARAMS_PTR; typedef struct CK_GOSTR3410_KEY_WRAP_PARAMS { CK_BYTE_PTR pWrapOID; CK_ULONG ulWrapOIDLen; CK_BYTE_PTR pUKM; CK_ULONG ulUKMLen; CK_OBJECT_HANDLE hKey; } CK_GOSTR3410_KEY_WRAP_PARAMS; typedef CK_GOSTR3410_KEY_WRAP_PARAMS CK_PTR CK_GOSTR3410_KEY_WRAP_PARAMS_PTR; typedef struct CK_SEED_CBC_ENCRYPT_DATA_PARAMS { CK_BYTE iv[16]; CK_BYTE_PTR pData; CK_ULONG length; } CK_SEED_CBC_ENCRYPT_DATA_PARAMS; typedef CK_SEED_CBC_ENCRYPT_DATA_PARAMS CK_PTR \ CK_SEED_CBC_ENCRYPT_DATA_PARAMS_PTR; #endif /* _PKCS11T_H_ */ python-pkcs11-0.7.0/extern/pkcs11f.h0000664000372000037200000006531113717606207017746 0ustar travistravis00000000000000/* Copyright (c) OASIS Open 2016. All Rights Reserved./ * /Distributed under the terms of the OASIS IPR Policy, * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others. */ /* Latest version of the specification: * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html */ /* This header file contains pretty much everything about all the * Cryptoki function prototypes. Because this information is * used for more than just declaring function prototypes, the * order of the functions appearing herein is important, and * should not be altered. */ /* General-purpose */ /* C_Initialize initializes the Cryptoki library. */ CK_PKCS11_FUNCTION_INFO(C_Initialize) #ifdef CK_NEED_ARG_LIST ( CK_VOID_PTR pInitArgs /* if this is not NULL_PTR, it gets * cast to CK_C_INITIALIZE_ARGS_PTR * and dereferenced */ ); #endif /* C_Finalize indicates that an application is done with the * Cryptoki library. */ CK_PKCS11_FUNCTION_INFO(C_Finalize) #ifdef CK_NEED_ARG_LIST ( CK_VOID_PTR pReserved /* reserved. Should be NULL_PTR */ ); #endif /* C_GetInfo returns general information about Cryptoki. */ CK_PKCS11_FUNCTION_INFO(C_GetInfo) #ifdef CK_NEED_ARG_LIST ( CK_INFO_PTR pInfo /* location that receives information */ ); #endif /* C_GetFunctionList returns the function list. */ CK_PKCS11_FUNCTION_INFO(C_GetFunctionList) #ifdef CK_NEED_ARG_LIST ( CK_FUNCTION_LIST_PTR_PTR ppFunctionList /* receives pointer to * function list */ ); #endif /* Slot and token management */ /* C_GetSlotList obtains a list of slots in the system. */ CK_PKCS11_FUNCTION_INFO(C_GetSlotList) #ifdef CK_NEED_ARG_LIST ( CK_BBOOL tokenPresent, /* only slots with tokens */ CK_SLOT_ID_PTR pSlotList, /* receives array of slot IDs */ CK_ULONG_PTR pulCount /* receives number of slots */ ); #endif /* C_GetSlotInfo obtains information about a particular slot in * the system. */ CK_PKCS11_FUNCTION_INFO(C_GetSlotInfo) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID, /* the ID of the slot */ CK_SLOT_INFO_PTR pInfo /* receives the slot information */ ); #endif /* C_GetTokenInfo obtains information about a particular token * in the system. */ CK_PKCS11_FUNCTION_INFO(C_GetTokenInfo) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID, /* ID of the token's slot */ CK_TOKEN_INFO_PTR pInfo /* receives the token information */ ); #endif /* C_GetMechanismList obtains a list of mechanism types * supported by a token. */ CK_PKCS11_FUNCTION_INFO(C_GetMechanismList) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID, /* ID of token's slot */ CK_MECHANISM_TYPE_PTR pMechanismList, /* gets mech. array */ CK_ULONG_PTR pulCount /* gets # of mechs. */ ); #endif /* C_GetMechanismInfo obtains information about a particular * mechanism possibly supported by a token. */ CK_PKCS11_FUNCTION_INFO(C_GetMechanismInfo) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID, /* ID of the token's slot */ CK_MECHANISM_TYPE type, /* type of mechanism */ CK_MECHANISM_INFO_PTR pInfo /* receives mechanism info */ ); #endif /* C_InitToken initializes a token. */ CK_PKCS11_FUNCTION_INFO(C_InitToken) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID, /* ID of the token's slot */ CK_UTF8CHAR_PTR pPin, /* the SO's initial PIN */ CK_ULONG ulPinLen, /* length in bytes of the PIN */ CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */ ); #endif /* C_InitPIN initializes the normal user's PIN. */ CK_PKCS11_FUNCTION_INFO(C_InitPIN) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_UTF8CHAR_PTR pPin, /* the normal user's PIN */ CK_ULONG ulPinLen /* length in bytes of the PIN */ ); #endif /* C_SetPIN modifies the PIN of the user who is logged in. */ CK_PKCS11_FUNCTION_INFO(C_SetPIN) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_UTF8CHAR_PTR pOldPin, /* the old PIN */ CK_ULONG ulOldLen, /* length of the old PIN */ CK_UTF8CHAR_PTR pNewPin, /* the new PIN */ CK_ULONG ulNewLen /* length of the new PIN */ ); #endif /* Session management */ /* C_OpenSession opens a session between an application and a * token. */ CK_PKCS11_FUNCTION_INFO(C_OpenSession) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID, /* the slot's ID */ CK_FLAGS flags, /* from CK_SESSION_INFO */ CK_VOID_PTR pApplication, /* passed to callback */ CK_NOTIFY Notify, /* callback function */ CK_SESSION_HANDLE_PTR phSession /* gets session handle */ ); #endif /* C_CloseSession closes a session between an application and a * token. */ CK_PKCS11_FUNCTION_INFO(C_CloseSession) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession /* the session's handle */ ); #endif /* C_CloseAllSessions closes all sessions with a token. */ CK_PKCS11_FUNCTION_INFO(C_CloseAllSessions) #ifdef CK_NEED_ARG_LIST ( CK_SLOT_ID slotID /* the token's slot */ ); #endif /* C_GetSessionInfo obtains information about the session. */ CK_PKCS11_FUNCTION_INFO(C_GetSessionInfo) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_SESSION_INFO_PTR pInfo /* receives session info */ ); #endif /* C_GetOperationState obtains the state of the cryptographic operation * in a session. */ CK_PKCS11_FUNCTION_INFO(C_GetOperationState) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pOperationState, /* gets state */ CK_ULONG_PTR pulOperationStateLen /* gets state length */ ); #endif /* C_SetOperationState restores the state of the cryptographic * operation in a session. */ CK_PKCS11_FUNCTION_INFO(C_SetOperationState) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pOperationState, /* holds state */ CK_ULONG ulOperationStateLen, /* holds state length */ CK_OBJECT_HANDLE hEncryptionKey, /* en/decryption key */ CK_OBJECT_HANDLE hAuthenticationKey /* sign/verify key */ ); #endif /* C_Login logs a user into a token. */ CK_PKCS11_FUNCTION_INFO(C_Login) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_USER_TYPE userType, /* the user type */ CK_UTF8CHAR_PTR pPin, /* the user's PIN */ CK_ULONG ulPinLen /* the length of the PIN */ ); #endif /* C_Logout logs a user out from a token. */ CK_PKCS11_FUNCTION_INFO(C_Logout) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession /* the session's handle */ ); #endif /* Object management */ /* C_CreateObject creates a new object. */ CK_PKCS11_FUNCTION_INFO(C_CreateObject) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_ATTRIBUTE_PTR pTemplate, /* the object's template */ CK_ULONG ulCount, /* attributes in template */ CK_OBJECT_HANDLE_PTR phObject /* gets new object's handle. */ ); #endif /* C_CopyObject copies an object, creating a new object for the * copy. */ CK_PKCS11_FUNCTION_INFO(C_CopyObject) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_OBJECT_HANDLE hObject, /* the object's handle */ CK_ATTRIBUTE_PTR pTemplate, /* template for new object */ CK_ULONG ulCount, /* attributes in template */ CK_OBJECT_HANDLE_PTR phNewObject /* receives handle of copy */ ); #endif /* C_DestroyObject destroys an object. */ CK_PKCS11_FUNCTION_INFO(C_DestroyObject) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_OBJECT_HANDLE hObject /* the object's handle */ ); #endif /* C_GetObjectSize gets the size of an object in bytes. */ CK_PKCS11_FUNCTION_INFO(C_GetObjectSize) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_OBJECT_HANDLE hObject, /* the object's handle */ CK_ULONG_PTR pulSize /* receives size of object */ ); #endif /* C_GetAttributeValue obtains the value of one or more object * attributes. */ CK_PKCS11_FUNCTION_INFO(C_GetAttributeValue) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_OBJECT_HANDLE hObject, /* the object's handle */ CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs; gets vals */ CK_ULONG ulCount /* attributes in template */ ); #endif /* C_SetAttributeValue modifies the value of one or more object * attributes. */ CK_PKCS11_FUNCTION_INFO(C_SetAttributeValue) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_OBJECT_HANDLE hObject, /* the object's handle */ CK_ATTRIBUTE_PTR pTemplate, /* specifies attrs and values */ CK_ULONG ulCount /* attributes in template */ ); #endif /* C_FindObjectsInit initializes a search for token and session * objects that match a template. */ CK_PKCS11_FUNCTION_INFO(C_FindObjectsInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_ATTRIBUTE_PTR pTemplate, /* attribute values to match */ CK_ULONG ulCount /* attrs in search template */ ); #endif /* C_FindObjects continues a search for token and session * objects that match a template, obtaining additional object * handles. */ CK_PKCS11_FUNCTION_INFO(C_FindObjects) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_OBJECT_HANDLE_PTR phObject, /* gets obj. handles */ CK_ULONG ulMaxObjectCount, /* max handles to get */ CK_ULONG_PTR pulObjectCount /* actual # returned */ ); #endif /* C_FindObjectsFinal finishes a search for token and session * objects. */ CK_PKCS11_FUNCTION_INFO(C_FindObjectsFinal) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession /* the session's handle */ ); #endif /* Encryption and decryption */ /* C_EncryptInit initializes an encryption operation. */ CK_PKCS11_FUNCTION_INFO(C_EncryptInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the encryption mechanism */ CK_OBJECT_HANDLE hKey /* handle of encryption key */ ); #endif /* C_Encrypt encrypts single-part data. */ CK_PKCS11_FUNCTION_INFO(C_Encrypt) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pData, /* the plaintext data */ CK_ULONG ulDataLen, /* bytes of plaintext */ CK_BYTE_PTR pEncryptedData, /* gets ciphertext */ CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */ ); #endif /* C_EncryptUpdate continues a multiple-part encryption * operation. */ CK_PKCS11_FUNCTION_INFO(C_EncryptUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pPart, /* the plaintext data */ CK_ULONG ulPartLen, /* plaintext data len */ CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ CK_ULONG_PTR pulEncryptedPartLen /* gets c-text size */ ); #endif /* C_EncryptFinal finishes a multiple-part encryption * operation. */ CK_PKCS11_FUNCTION_INFO(C_EncryptFinal) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session handle */ CK_BYTE_PTR pLastEncryptedPart, /* last c-text */ CK_ULONG_PTR pulLastEncryptedPartLen /* gets last size */ ); #endif /* C_DecryptInit initializes a decryption operation. */ CK_PKCS11_FUNCTION_INFO(C_DecryptInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the decryption mechanism */ CK_OBJECT_HANDLE hKey /* handle of decryption key */ ); #endif /* C_Decrypt decrypts encrypted data in a single part. */ CK_PKCS11_FUNCTION_INFO(C_Decrypt) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pEncryptedData, /* ciphertext */ CK_ULONG ulEncryptedDataLen, /* ciphertext length */ CK_BYTE_PTR pData, /* gets plaintext */ CK_ULONG_PTR pulDataLen /* gets p-text size */ ); #endif /* C_DecryptUpdate continues a multiple-part decryption * operation. */ CK_PKCS11_FUNCTION_INFO(C_DecryptUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pEncryptedPart, /* encrypted data */ CK_ULONG ulEncryptedPartLen, /* input length */ CK_BYTE_PTR pPart, /* gets plaintext */ CK_ULONG_PTR pulPartLen /* p-text size */ ); #endif /* C_DecryptFinal finishes a multiple-part decryption * operation. */ CK_PKCS11_FUNCTION_INFO(C_DecryptFinal) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pLastPart, /* gets plaintext */ CK_ULONG_PTR pulLastPartLen /* p-text size */ ); #endif /* Message digesting */ /* C_DigestInit initializes a message-digesting operation. */ CK_PKCS11_FUNCTION_INFO(C_DigestInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism /* the digesting mechanism */ ); #endif /* C_Digest digests data in a single part. */ CK_PKCS11_FUNCTION_INFO(C_Digest) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pData, /* data to be digested */ CK_ULONG ulDataLen, /* bytes of data to digest */ CK_BYTE_PTR pDigest, /* gets the message digest */ CK_ULONG_PTR pulDigestLen /* gets digest length */ ); #endif /* C_DigestUpdate continues a multiple-part message-digesting * operation. */ CK_PKCS11_FUNCTION_INFO(C_DigestUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pPart, /* data to be digested */ CK_ULONG ulPartLen /* bytes of data to be digested */ ); #endif /* C_DigestKey continues a multi-part message-digesting * operation, by digesting the value of a secret key as part of * the data already digested. */ CK_PKCS11_FUNCTION_INFO(C_DigestKey) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_OBJECT_HANDLE hKey /* secret key to digest */ ); #endif /* C_DigestFinal finishes a multiple-part message-digesting * operation. */ CK_PKCS11_FUNCTION_INFO(C_DigestFinal) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pDigest, /* gets the message digest */ CK_ULONG_PTR pulDigestLen /* gets byte count of digest */ ); #endif /* Signing and MACing */ /* C_SignInit initializes a signature (private key encryption) * operation, where the signature is (will be) an appendix to * the data, and plaintext cannot be recovered from the * signature. */ CK_PKCS11_FUNCTION_INFO(C_SignInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ CK_OBJECT_HANDLE hKey /* handle of signature key */ ); #endif /* C_Sign signs (encrypts with private key) data in a single * part, where the signature is (will be) an appendix to the * data, and plaintext cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_Sign) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pData, /* the data to sign */ CK_ULONG ulDataLen, /* count of bytes to sign */ CK_BYTE_PTR pSignature, /* gets the signature */ CK_ULONG_PTR pulSignatureLen /* gets signature length */ ); #endif /* C_SignUpdate continues a multiple-part signature operation, * where the signature is (will be) an appendix to the data, * and plaintext cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_SignUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pPart, /* the data to sign */ CK_ULONG ulPartLen /* count of bytes to sign */ ); #endif /* C_SignFinal finishes a multiple-part signature operation, * returning the signature. */ CK_PKCS11_FUNCTION_INFO(C_SignFinal) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pSignature, /* gets the signature */ CK_ULONG_PTR pulSignatureLen /* gets signature length */ ); #endif /* C_SignRecoverInit initializes a signature operation, where * the data can be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_SignRecoverInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the signature mechanism */ CK_OBJECT_HANDLE hKey /* handle of the signature key */ ); #endif /* C_SignRecover signs data in a single operation, where the * data can be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_SignRecover) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pData, /* the data to sign */ CK_ULONG ulDataLen, /* count of bytes to sign */ CK_BYTE_PTR pSignature, /* gets the signature */ CK_ULONG_PTR pulSignatureLen /* gets signature length */ ); #endif /* Verifying signatures and MACs */ /* C_VerifyInit initializes a verification operation, where the * signature is an appendix to the data, and plaintext cannot * cannot be recovered from the signature (e.g. DSA). */ CK_PKCS11_FUNCTION_INFO(C_VerifyInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ CK_OBJECT_HANDLE hKey /* verification key */ ); #endif /* C_Verify verifies a signature in a single-part operation, * where the signature is an appendix to the data, and plaintext * cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_Verify) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pData, /* signed data */ CK_ULONG ulDataLen, /* length of signed data */ CK_BYTE_PTR pSignature, /* signature */ CK_ULONG ulSignatureLen /* signature length*/ ); #endif /* C_VerifyUpdate continues a multiple-part verification * operation, where the signature is an appendix to the data, * and plaintext cannot be recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_VerifyUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pPart, /* signed data */ CK_ULONG ulPartLen /* length of signed data */ ); #endif /* C_VerifyFinal finishes a multiple-part verification * operation, checking the signature. */ CK_PKCS11_FUNCTION_INFO(C_VerifyFinal) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pSignature, /* signature to verify */ CK_ULONG ulSignatureLen /* signature length */ ); #endif /* C_VerifyRecoverInit initializes a signature verification * operation, where the data is recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_VerifyRecoverInit) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the verification mechanism */ CK_OBJECT_HANDLE hKey /* verification key */ ); #endif /* C_VerifyRecover verifies a signature in a single-part * operation, where the data is recovered from the signature. */ CK_PKCS11_FUNCTION_INFO(C_VerifyRecover) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pSignature, /* signature to verify */ CK_ULONG ulSignatureLen, /* signature length */ CK_BYTE_PTR pData, /* gets signed data */ CK_ULONG_PTR pulDataLen /* gets signed data len */ ); #endif /* Dual-function cryptographic operations */ /* C_DigestEncryptUpdate continues a multiple-part digesting * and encryption operation. */ CK_PKCS11_FUNCTION_INFO(C_DigestEncryptUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pPart, /* the plaintext data */ CK_ULONG ulPartLen, /* plaintext length */ CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ ); #endif /* C_DecryptDigestUpdate continues a multiple-part decryption and * digesting operation. */ CK_PKCS11_FUNCTION_INFO(C_DecryptDigestUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pEncryptedPart, /* ciphertext */ CK_ULONG ulEncryptedPartLen, /* ciphertext length */ CK_BYTE_PTR pPart, /* gets plaintext */ CK_ULONG_PTR pulPartLen /* gets plaintext len */ ); #endif /* C_SignEncryptUpdate continues a multiple-part signing and * encryption operation. */ CK_PKCS11_FUNCTION_INFO(C_SignEncryptUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pPart, /* the plaintext data */ CK_ULONG ulPartLen, /* plaintext length */ CK_BYTE_PTR pEncryptedPart, /* gets ciphertext */ CK_ULONG_PTR pulEncryptedPartLen /* gets c-text length */ ); #endif /* C_DecryptVerifyUpdate continues a multiple-part decryption and * verify operation. */ CK_PKCS11_FUNCTION_INFO(C_DecryptVerifyUpdate) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_BYTE_PTR pEncryptedPart, /* ciphertext */ CK_ULONG ulEncryptedPartLen, /* ciphertext length */ CK_BYTE_PTR pPart, /* gets plaintext */ CK_ULONG_PTR pulPartLen /* gets p-text length */ ); #endif /* Key management */ /* C_GenerateKey generates a secret key, creating a new key * object. */ CK_PKCS11_FUNCTION_INFO(C_GenerateKey) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* key generation mech. */ CK_ATTRIBUTE_PTR pTemplate, /* template for new key */ CK_ULONG ulCount, /* # of attrs in template */ CK_OBJECT_HANDLE_PTR phKey /* gets handle of new key */ ); #endif /* C_GenerateKeyPair generates a public-key/private-key pair, * creating new key objects. */ CK_PKCS11_FUNCTION_INFO(C_GenerateKeyPair) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session handle */ CK_MECHANISM_PTR pMechanism, /* key-gen mech. */ CK_ATTRIBUTE_PTR pPublicKeyTemplate, /* template for pub. key */ CK_ULONG ulPublicKeyAttributeCount, /* # pub. attrs. */ CK_ATTRIBUTE_PTR pPrivateKeyTemplate, /* template for priv. key */ CK_ULONG ulPrivateKeyAttributeCount, /* # priv. attrs. */ CK_OBJECT_HANDLE_PTR phPublicKey, /* gets pub. key handle */ CK_OBJECT_HANDLE_PTR phPrivateKey /* gets priv. key handle */ ); #endif /* C_WrapKey wraps (i.e., encrypts) a key. */ CK_PKCS11_FUNCTION_INFO(C_WrapKey) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_MECHANISM_PTR pMechanism, /* the wrapping mechanism */ CK_OBJECT_HANDLE hWrappingKey, /* wrapping key */ CK_OBJECT_HANDLE hKey, /* key to be wrapped */ CK_BYTE_PTR pWrappedKey, /* gets wrapped key */ CK_ULONG_PTR pulWrappedKeyLen /* gets wrapped key size */ ); #endif /* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new * key object. */ CK_PKCS11_FUNCTION_INFO(C_UnwrapKey) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_MECHANISM_PTR pMechanism, /* unwrapping mech. */ CK_OBJECT_HANDLE hUnwrappingKey, /* unwrapping key */ CK_BYTE_PTR pWrappedKey, /* the wrapped key */ CK_ULONG ulWrappedKeyLen, /* wrapped key len */ CK_ATTRIBUTE_PTR pTemplate, /* new key template */ CK_ULONG ulAttributeCount, /* template length */ CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ ); #endif /* C_DeriveKey derives a key from a base key, creating a new key * object. */ CK_PKCS11_FUNCTION_INFO(C_DeriveKey) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* session's handle */ CK_MECHANISM_PTR pMechanism, /* key deriv. mech. */ CK_OBJECT_HANDLE hBaseKey, /* base key */ CK_ATTRIBUTE_PTR pTemplate, /* new key template */ CK_ULONG ulAttributeCount, /* template length */ CK_OBJECT_HANDLE_PTR phKey /* gets new handle */ ); #endif /* Random number generation */ /* C_SeedRandom mixes additional seed material into the token's * random number generator. */ CK_PKCS11_FUNCTION_INFO(C_SeedRandom) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR pSeed, /* the seed material */ CK_ULONG ulSeedLen /* length of seed material */ ); #endif /* C_GenerateRandom generates random data. */ CK_PKCS11_FUNCTION_INFO(C_GenerateRandom) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession, /* the session's handle */ CK_BYTE_PTR RandomData, /* receives the random data */ CK_ULONG ulRandomLen /* # of bytes to generate */ ); #endif /* Parallel function management */ /* C_GetFunctionStatus is a legacy function; it obtains an * updated status of a function running in parallel with an * application. */ CK_PKCS11_FUNCTION_INFO(C_GetFunctionStatus) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession /* the session's handle */ ); #endif /* C_CancelFunction is a legacy function; it cancels a function * running in parallel. */ CK_PKCS11_FUNCTION_INFO(C_CancelFunction) #ifdef CK_NEED_ARG_LIST ( CK_SESSION_HANDLE hSession /* the session's handle */ ); #endif /* C_WaitForSlotEvent waits for a slot event (token insertion, * removal, etc.) to occur. */ CK_PKCS11_FUNCTION_INFO(C_WaitForSlotEvent) #ifdef CK_NEED_ARG_LIST ( CK_FLAGS flags, /* blocking/nonblocking flag */ CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */ CK_VOID_PTR pRserved /* reserved. Should be NULL_PTR */ ); #endif python-pkcs11-0.7.0/setup.cfg0000664000372000037200000000004613717606456016641 0ustar travistravis00000000000000[egg_info] tag_build = tag_date = 0 python-pkcs11-0.7.0/.travis.yml0000664000372000037200000000327413717606207017131 0ustar travistravis00000000000000sudo: false language: python python: - '3.5' - '3.6' - '3.7' - '3.8' env: global: - PKCS11_MODULE=/home/travis/lib/softhsm/libsofthsm2.so - PKCS11_TOKEN_LABEL=TEST - PKCS11_TOKEN_PIN=1234 - PKCS11_TOKEN_SO_PIN=5678 cache: - pip - ccache # For SoftHSMv2 before_install: - pip install -U pip setuptools - pip install -r dev-requirements.txt # Install SoftHSMv2 - curl https://dist.opendnssec.org/source/softhsm-2.5.0.tar.gz | tar -zxv - (cd softhsm-2.5.0 && ./configure --prefix=$HOME --disable-p11-kit --disable-gost && make all install CC="ccache gcc" CXX="ccache g++") before_script: # Initialise a token on the SoftHSM - $HOME/bin/softhsm2-util --init-token --free --label TEST --pin 1234 --so-pin 5678 # Build our extension - python setup.py build_ext -i script: python -m unittest deploy: provider: pypi user: danni password: secure: "A/W51+GTE9CBAm4m+1AVg11EAF63BUBrCXIonmYCdTT2htEGStk9AJnZGOinHPhwgJoWujBqgqyjqm8wJSvsmhyPSWxGk20lkCJOptcHdExu4FoSnLNNzAgPtZH5lLarkpvxB20J9hUUb4CQbgz5BWeNqFPvKigKFworCksRr9EM4J/Ys8tmkI2zwSTRDH2YAmhI/h8BWGpHMP+pNUsjlp9ZbDaxgNY85r7RloP07N5R0A7TPePH8wJzuGMDOv8dLazdr0epCbvFk+2CyJ7KiEJoX+SlS/2Hi7OKnmuf7QG2z2YyukLlJcP+IhRfzZDVgUeXwJbu24XAUdMoBS8OxId8dOKFla+GJScpWGpA9rO5vgItTAYLG7sd9HuveCtvUZxqbJd5teST4PdcxjjeO5LxYkgXKrLEo1dvDtPOm/veA0axFrXzlberJCKyN2T6grfM5QVUCORQnUYPnOqkYXMHFKSIUfa2mpfJ8NZaHR7jEbddU/PpQTHwlcehMtTx9IKQyfzillmhiXVc+UMOInFbEsU4oD9f0eP2fcs2dDB3ppR+Rdkh8bb80zH2r55Giu4Fv/WGcllwaYvMGkm6TBdod/Hva4sypJaLkLFDH6LQ0jOBHfPdFYKzEn16kZ1F4X+QWl6lKiz4XWAJI8Cf73y9Acj1Q+4MAHobkE/908M=" skip_upload_docs: true on: tags: true python: 3.6 python-pkcs11-0.7.0/dev-requirements.in0000664000372000037200000000013713717606207020642 0ustar travistravis00000000000000Cython setuptools_scm # Used for tests oscrypto cryptography sphinx sphinx-rtd-theme flake8 python-pkcs11-0.7.0/requirements.in0000664000372000037200000000007113717606207020063 0ustar travistravis00000000000000aenum; python_version < "3.6" asn1crypto cached-property python-pkcs11-0.7.0/README.rst0000664000372000037200000003626113717606207016511 0ustar travistravis00000000000000Python PKCS#11 - High Level Wrapper API ======================================= A high level, "more Pythonic" interface to the PKCS#11 (Cryptoki) standard to support HSM and Smartcard devices in Python. The interface is designed to follow the logical structure of a HSM, with useful defaults for obscurely documented parameters. Many APIs will optionally accept iterables and act as generators, allowing you to stream large data blocks for symmetric encryption. python-pkcs11 also includes numerous utility functions to convert between PKCS #11 data structures and common interchange formats including PKCS #1 and X.509. python-pkcs11 is fully documented and has a full integration test suite for all features, with continuous integration against multiple HSM platforms including: * Thales nCipher * Opencryptoki TPM * OpenSC/Smartcard-HSM/Nitrokey HSM Source: https://github.com/danni/python-pkcs11 Documentation: http://python-pkcs11.readthedocs.io/en/latest/ Getting Started --------------- Install from Pip: :: pip install python-pkcs11 Or build from source: :: python setup.py build Assuming your PKCS#11 library is set as `PKCS11_MODULE` and contains a token named `DEMO`: AES ~~~ :: import pkcs11 # Initialise our PKCS#11 library lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an AES key in this session key = session.generate_key(pkcs11.KeyType.AES, 256) # Get an initialisation vector iv = session.generate_random(128) # AES blocks are fixed at 128 bits # Encrypt our data crypttext = key.encrypt(data, mechanism_param=iv) 3DES ~~~~ :: import pkcs11 # Initialise our PKCS#11 library lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate a DES key in this session key = session.generate_key(pkcs11.KeyType.DES3) # Get an initialisation vector iv = session.generate_random(64) # DES blocks are fixed at 64 bits # Encrypt our data crypttext = key.encrypt(data, mechanism_param=iv) RSA ~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an RSA keypair in this session pub, priv = session.generate_keypair(pkcs11.KeyType.RSA, 2048) # Encrypt as one block crypttext = pub.encrypt(data) DSA ~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an DSA keypair in this session pub, priv = session.generate_keypair(pkcs11.KeyType.DSA, 1024) # Sign signature = priv.sign(data) ECDSA ~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') data = b'INPUT DATA' # Open a session on our token with token.open(user_pin='1234') as session: # Generate an EC keypair in this session from a named curve ecparams = session.create_domain_parameters( pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: pkcs11.util.ec.encode_named_curve_parameters('prime256v1'), }, local=True) pub, priv = ecparams.generate_keypair() # Sign signature = priv.sign(data) Diffie-Hellman ~~~~~~~~~~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') with token.open() as session: # Given shared Diffie-Hellman parameters parameters = session.create_domain_parameters(pkcs11.KeyType.DH, { pkcs11.Attribute.PRIME: prime, # Diffie-Hellman parameters pkcs11.Attribute.BASE: base, }) # Generate a DH key pair from the public parameters public, private = parameters.generate_keypair() # Share the public half of it with our other party. _network_.write(public[Attribute.VALUE]) # And get their shared value other_value = _network_.read() # Derive a shared session key with perfect forward secrecy session_key = private.derive_key( pkcs11.KeyType.AES, 128, mechanism_param=other_value) Elliptic-Curve Diffie-Hellman ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: import pkcs11 lib = pkcs11.lib(os.environ['PKCS11_MODULE']) token = lib.get_token(token_label='DEMO') with token.open() as session: # Given DER encocded EC parameters, e.g. from # openssl ecparam -outform der -name parameters = session.create_domain_parameters(pkcs11.KeyType.EC, { pkcs11.Attribute.EC_PARAMS: ecparams, }) # Generate a DH key pair from the public parameters public, private = parameters.generate_keypair() # Share the public half of it with our other party. _network_.write(public[pkcs11.Attribute.EC_POINT]) # And get their shared value other_value = _network_.read() # Derive a shared session key session_key = private.derive_key( pkcs11.KeyType.AES, 128, mechanism_param=(pkcs11.KDF.NULL, None, other_value)) Tested Compatibility -------------------- +------------------------------+--------------+-----------------+--------------+-------------------+ | Functionality | SoftHSMv2 | Thales nCipher | Opencryptoki | OpenSC (Nitrokey) | +==============================+==============+=================+==============+===================+ | Get Slots/Tokens | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Get Mechanisms | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Initialize token | Not implemented | +------------------------------+-------------------------------------------------------------------+ | Slot events | Not implemented | +------------------------------+-------------------------------------------------------------------+ | Alternative authentication | Not implemented | | path | | +------------------------------+-------------------------------------------------------------------+ | `Always authenticate` keys | Not implemented | +-------------+----------------+--------------+-----------------+--------------+-------------------+ | Create/Copy | Keys | Works | Works | Errors | Create | | +----------------+--------------+-----------------+--------------+-------------------+ | | Certificates | Caveats [1]_ | Caveats [1]_ | Caveats [1]_ | ? | | +----------------+--------------+-----------------+--------------+-------------------+ | | Domain Params | Caveats [1]_ | Caveats [1]_ | ? | N/A | +-------------+----------------+--------------+-----------------+--------------+-------------------+ | Destroy Object | Works | N/A | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Generate Random | Works | Works | Works | Works | +------------------------------+--------------+-----------------+--------------+-------------------+ | Seed Random | Works | N/A | N/A | N/A | +------------------------------+--------------+-----------------+--------------+-------------------+ | Digest (Data & Keys) | Works | Caveats [2]_ | Works | Works | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | AES | Generate key | Works | Works | Works | N/A | | +---------------------+--------------+-----------------+--------------+ | | | Encrypt/Decrypt | Works | Works | Works | | | +---------------------+--------------+-----------------+--------------+ | | | Wrap/Unwrap | ? [3]_ | Works | Errors | | | +---------------------+--------------+-----------------+--------------+ | | | Sign/Verify | Works | Works [4]_ | N/A | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DES2/ | Generate key | Works | Works | Works | N/A | | DES3 +---------------------+--------------+-----------------+--------------+ | | | Encrypt/Decrypt | Works | Works | Works | | | +---------------------+--------------+-----------------+--------------+ | | | Wrap/Unwrap | ? | ? | ? | | | +---------------------+--------------+-----------------+--------------+ | | | Sign/Verify | ? | ? | ? | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | RSA | Generate key pair | Works | Works | Works | Works [4]_ [8]_ | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Encrypt/Decrypt | Works | Works | Works | Decrypt only [9]_ | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Wrap/Unwrap | Works | Works | Works | N/A | | +---------------------+--------------+-----------------+--------------+-------------------+ | | Sign/Verify | Works | Works | Works | Works | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DSA | Generate parameters | Works | Error | N/A | N/A | | +---------------------+--------------+-----------------+ | | | | Generate key pair | Works | Caveats [5]_ | | | | +---------------------+--------------+-----------------+ | | | | Sign/Verify | Works | Works [4]_ | | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | DH | Generate parameters | Works | N/A | N/A | N/A | | +---------------------+--------------+-----------------+ | | | | Generate key pair | Works | Caveats [6]_ | | | | +---------------------+--------------+-----------------+ | | | | Derive Key | Works | Caveats [7]_ | | | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | EC | Generate key pair | Caveats [6]_ | ? [3]_ | N/A | Works | | +---------------------+--------------+-----------------+ +-------------------+ | | Sign/Verify (ECDSA) | Works [4]_ | ? [3]_ | | Sign only [9]_ | | +---------------------+--------------+-----------------+ +-------------------+ | | Derive key (ECDH) | Works | ? [3]_ | | ? | +--------+---------------------+--------------+-----------------+--------------+-------------------+ | Proprietary extensions | N/A | Not implemented | N/A | N/A | +------------------------------+--------------+-----------------+--------------+-------------------+ .. [1] Device supports limited set of attributes. .. [2] Digesting keys is not supported. .. [3] Untested: requires support in device. .. [4] Default mechanism not supported, must specify a mechanism. .. [5] From existing domain parameters. .. [6] Local domain parameters only. .. [7] Generates security warnings about the derived key. .. [8] `store` parameter is ignored, all keys are stored. .. [9] Encryption/verify not supported, extract the public key Python version: * 3.4 (with `aenum`) * 3.5 (with `aenum`) * 3.6 PKCS#11 versions: * 2.11 * 2.20 * 2.40 Feel free to send pull requests for any functionality that's not exposed. The code is designed to be readable and expose the PKCS #11 spec in a straight-forward way. If you want your device supported, get in touch! More info on PKCS #11 --------------------- The latest version of the PKCS #11 spec is available from OASIS: http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html You should also consult the documentation for your PKCS #11 implementation. Many implementations expose additional vendor options configurable in your environment, including alternative features, modes and debugging information. License ------- MIT License Copyright (c) 2017 Danielle Madeley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-pkcs11-0.7.0/tools/0000775000372000037200000000000013717606456016160 5ustar travistravis00000000000000python-pkcs11-0.7.0/tools/nfast/0000775000372000037200000000000013717606456017273 5ustar travistravis00000000000000python-pkcs11-0.7.0/tools/nfast/build.sh0000775000372000037200000000026213717606207020723 0ustar travistravis00000000000000#!/bin/sh # # Build pkcs11 # set -xe # Enable Python 3.5 from SCL . /opt/rh/rh-python35/enable # Enable our virtualenv . python_env/bin/activate python setup.py build_ext -i python-pkcs11-0.7.0/tools/nfast/install.sh0000775000372000037200000000057313717606207021277 0ustar travistravis00000000000000#!/bin/sh # # Install dependencies for nFast tests on RHEL7 # set -xe # Enable Python 3.5 from SCL . /opt/rh/rh-python35/enable # Create virtualenv if needed [ -d python_env ] || virtualenv -p python3 python_env # Enable our virtualenv . python_env/bin/activate pip install -U pip six pip install -U setuptools cython pip install -r requirements.txt -r dev-requirements.txt python-pkcs11-0.7.0/tools/nfast/test.sh0000775000372000037200000000065113717606207020605 0ustar travistravis00000000000000#!/bin/sh # # Test pkcs11 # set -xe # Enable Python 3.5 from SCL . /opt/rh/rh-python35/enable # Enable our virtualenv . python_env/bin/activate # Test parameters export CKNFAST_FAKE_ACCELERATOR_LOGIN=true export CKNFAST_LOADSHARING=1 export CKNFAST_DEBUG=6 export PKCS11_MODULE=/opt/nfast/toolkits/pkcs11/libcknfast.so export PKCS11_TOKEN_LABEL='loadshared accelerator' export PKCS11_TOKEN_PIN='0000' python -m unittest python-pkcs11-0.7.0/tools/buildbot/0000775000372000037200000000000013717606456017764 5ustar travistravis00000000000000python-pkcs11-0.7.0/tools/buildbot/build.sh0000775000372000037200000000016713717606207021420 0ustar travistravis00000000000000#!/bin/sh # # Build pkcs11 # set -xe # Enable our virtualenv . python_env/bin/activate python setup.py build_ext -i python-pkcs11-0.7.0/tools/buildbot/install.sh0000775000372000037200000000044113717606207021762 0ustar travistravis00000000000000#!/bin/sh # # Install dependencies # set -xe # Create virtualenv if needed [ -d python_env ] || python3 -m venv python_env # Enable our virtualenv . python_env/bin/activate pip install -U pip six pip install -U setuptools cython pip install -r requirements.txt -r dev-requirements.txt python-pkcs11-0.7.0/tools/buildbot/test.sh0000775000372000037200000000034613717606207021277 0ustar travistravis00000000000000#!/bin/sh # # Test pkcs11 # set -xe # Enable our virtualenv . python_env/bin/activate # Test parameters come from ShellCommand # export PKCS11_MODULE= # export PKCS11_TOKEN_LABEL= # export PKCS11_TOKEN_PIN= python -m unittest python-pkcs11-0.7.0/dev-requirements.txt0000664000372000037200000000345313717606207021057 0ustar travistravis00000000000000# # This file is autogenerated by pip-compile # To update, run: # # pip-compile dev-requirements.in # alabaster==0.7.12 # via sphinx asn1crypto==1.3.0 # via oscrypto babel==2.8.0 # via sphinx certifi==2019.11.28 # via requests cffi==1.14.0 # via cryptography chardet==3.0.4 # via requests cryptography==2.8 # via -r dev-requirements.in cython==0.29.15 # via -r dev-requirements.in docutils==0.16 # via sphinx entrypoints==0.3 # via flake8 flake8==3.7.9 # via -r dev-requirements.in idna==2.9 # via requests imagesize==1.2.0 # via sphinx jinja2==2.11.1 # via sphinx markupsafe==1.1.1 # via jinja2 mccabe==0.6.1 # via flake8 oscrypto==1.2.0 # via -r dev-requirements.in packaging==20.1 # via sphinx pycodestyle==2.5.0 # via flake8 pycparser==2.19 # via cffi pyflakes==2.1.1 # via flake8 pygments==2.5.2 # via sphinx pyparsing==2.4.6 # via packaging pytz==2019.3 # via babel requests==2.23.0 # via sphinx setuptools-scm==3.5.0 # via -r dev-requirements.in six==1.14.0 # via cryptography, packaging snowballstemmer==2.0.0 # via sphinx sphinx-rtd-theme==0.4.3 # via -r dev-requirements.in sphinx==2.4.3 # via -r dev-requirements.in, sphinx-rtd-theme sphinxcontrib-applehelp==1.0.1 # via sphinx sphinxcontrib-devhelp==1.0.1 # via sphinx sphinxcontrib-htmlhelp==1.0.3 # via sphinx sphinxcontrib-jsmath==1.0.1 # via sphinx sphinxcontrib-qthelp==1.0.2 # via sphinx sphinxcontrib-serializinghtml==1.1.3 # via sphinx urllib3==1.25.8 # via requests # The following packages are considered to be unsafe in a requirements file: # setuptools python-pkcs11-0.7.0/setup.py0000775000372000037200000000350713717606207016534 0ustar travistravis00000000000000#!/usr/bin/env python """ setup.py """ from setuptools import setup, find_packages from setuptools.extension import Extension import platform # if compiling using MSVC, we need to link against user32 library if platform.system() == 'Windows': libraries = ('user32',) else: libraries = () if __name__ == '__main__': with \ open('requirements.in') as requirements, \ open('README.rst') as readme: ext_modules = [ Extension('pkcs11._pkcs11', sources=[ 'pkcs11/_pkcs11.pyx', ], libraries=libraries, ), ] setup( name='python-pkcs11', description='PKCS#11 (Cryptoki) support for Python', use_scm_version=True, author='Danielle Madeley', author_email='danielle@madeley.id.au', url='https://github.com/danni/python-pkcs11', long_description=readme.read(), classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Security :: Cryptography', ], packages=find_packages(exclude=['tests']), include_package_data=True, ext_modules=ext_modules, install_requires=requirements.readlines(), setup_requires=[ 'cython', 'setuptools >= 18.0', 'setuptools_scm', ], test_suite='tests', ) python-pkcs11-0.7.0/tests/0000775000372000037200000000000013717606456016162 5ustar travistravis00000000000000python-pkcs11-0.7.0/tests/test_rsa.py0000664000372000037200000001055413717606207020357 0ustar travistravis00000000000000""" PKCS#11 RSA Public Key Cryptography """ import pkcs11 from pkcs11 import Attribute, KeyType, ObjectClass, Mechanism, MGF from . import TestCase, requires, FIXME class RSATests(TestCase): @requires(Mechanism.RSA_PKCS_KEY_PAIR_GEN) def setUp(self): super().setUp() self.public, self.private = \ self.session.generate_keypair(KeyType.RSA, 1024) @requires(Mechanism.RSA_PKCS) def test_sign_pkcs_v15(self): data = b'00000000' signature = self.private.sign(data, mechanism=Mechanism.RSA_PKCS) self.assertIsNotNone(signature) self.assertIsInstance(signature, bytes) self.assertTrue(self.public.verify(data, signature, mechanism=Mechanism.RSA_PKCS)) self.assertFalse(self.public.verify(data, b'1234', mechanism=Mechanism.RSA_PKCS)) @requires(Mechanism.SHA512_RSA_PKCS) def test_sign_default(self): data = b'HELLO WORLD' * 1024 signature = self.private.sign(data) self.assertIsNotNone(signature) self.assertIsInstance(signature, bytes) self.assertTrue(self.public.verify(data, signature)) self.assertFalse(self.public.verify(data, b'1234')) @requires(Mechanism.SHA512_RSA_PKCS) def test_sign_stream(self): data = ( b'I' * 16, b'N' * 16, b'P' * 16, b'U' * 16, b'T' * 10, # don't align to the blocksize ) signature = self.private.sign(data) self.assertIsNotNone(signature) self.assertIsInstance(signature, bytes) self.assertTrue(self.public.verify(data, signature)) @requires(Mechanism.RSA_PKCS_OAEP) @FIXME.opencryptoki # can't set key attributes def test_key_wrap(self): key = self.session.generate_key(KeyType.AES, 128, template={ Attribute.EXTRACTABLE: True, Attribute.SENSITIVE: False, }) data = self.public.wrap_key(key) self.assertNotEqual(data, key[Attribute.VALUE]) key2 = self.private.unwrap_key(ObjectClass.SECRET_KEY, KeyType.AES, data, template={ Attribute.EXTRACTABLE: True, Attribute.SENSITIVE: False, }) self.assertEqual(key[Attribute.VALUE], key2[Attribute.VALUE]) @requires(Mechanism.RSA_PKCS_OAEP) def test_encrypt_oaep(self): data = b'SOME DATA' crypttext = self.public.encrypt(data, mechanism=Mechanism.RSA_PKCS_OAEP, mechanism_param=(Mechanism.SHA_1, MGF.SHA1, None)) self.assertNotEqual(data, crypttext) plaintext = self.private.decrypt(crypttext, mechanism=Mechanism.RSA_PKCS_OAEP, mechanism_param=(Mechanism.SHA_1, MGF.SHA1, None)) self.assertEqual(data, plaintext) @requires(Mechanism.SHA1_RSA_PKCS_PSS) def test_sign_pss(self): data = b'SOME DATA' # These are the default params signature = self.private.sign(data, mechanism=Mechanism.SHA1_RSA_PKCS_PSS, mechanism_param=(Mechanism.SHA_1, MGF.SHA1, 20)) self.assertTrue(self.public.verify( data, signature, mechanism=Mechanism.SHA1_RSA_PKCS_PSS)) @requires(Mechanism.RSA_PKCS_OAEP) def test_encrypt_too_much_data(self): data = b'1234' * 128 # You can't encrypt lots of data with RSA # This should ideally throw DataLen but you can't trust it with self.assertRaises(pkcs11.PKCS11Error): self.public.encrypt(data) python-pkcs11-0.7.0/tests/test_slots_and_tokens.py0000664000372000037200000000433413717606207023142 0ustar travistravis00000000000000""" PKCS#11 Slots and Tokens """ import unittest import pkcs11 from . import LIB, TOKEN, Only, Not class SlotsAndTokensTests(unittest.TestCase): def test_double_initialise(self): self.assertIsNotNone(pkcs11.lib(LIB)) self.assertIsNotNone(pkcs11.lib(LIB)) def test_double_initialise_different_libs(self): self.assertIsNotNone(pkcs11.lib(LIB)) with self.assertRaises(pkcs11.AlreadyInitialized): pkcs11.lib('somethingelse.so') @Only.softhsm2 def test_get_slots(self): lib = pkcs11.lib(LIB) slots = lib.get_slots() self.assertEqual(len(slots), 2) slot1, slot2 = slots self.assertIsInstance(slot1, pkcs11.Slot) self.assertEqual(slot1.flags, pkcs11.SlotFlag.TOKEN_PRESENT) def test_get_mechanisms(self): lib = pkcs11.lib(LIB) slot, *_ = lib.get_slots() mechanisms = slot.get_mechanisms() self.assertIn(pkcs11.Mechanism.RSA_PKCS, mechanisms) def test_get_mechanism_info(self): lib = pkcs11.lib(LIB) slot, *_ = lib.get_slots() info = slot.get_mechanism_info(pkcs11.Mechanism.RSA_PKCS_OAEP) self.assertIsInstance(info, pkcs11.MechanismInfo) @Not.nfast # EC not supported @Not.opencryptoki def test_get_mechanism_info_ec(self): lib = pkcs11.lib(LIB) slot, *_ = lib.get_slots() info = slot.get_mechanism_info(pkcs11.Mechanism.EC_KEY_PAIR_GEN) self.assertIsInstance(info, pkcs11.MechanismInfo) self.assertIn(pkcs11.MechanismFlag.EC_NAMEDCURVE, info.flags) @Only.softhsm2 def test_get_tokens(self): lib = pkcs11.lib(LIB) tokens = lib.get_tokens(token_flags=pkcs11.TokenFlag.RNG) self.assertEqual(len(list(tokens)), 2) tokens = lib.get_tokens(token_label=TOKEN) self.assertEqual(len(list(tokens)), 1) @Only.softhsm2 def test_get_token(self): lib = pkcs11.lib(LIB) slot, *_ = lib.get_slots() token = slot.get_token() self.assertIsInstance(token, pkcs11.Token) self.assertEqual(token.label, TOKEN) self.assertIn(pkcs11.TokenFlag.TOKEN_INITIALIZED, token.flags) self.assertIn(pkcs11.TokenFlag.LOGIN_REQUIRED, token.flags) python-pkcs11-0.7.0/tests/test_dh.py0000664000372000037200000001323613717606207020165 0ustar travistravis00000000000000""" PKCS#11 Diffie-Hellman tests """ import base64 from pkcs11 import Attribute, KeyType, DomainParameters, Mechanism from pkcs11.util.dh import ( decode_dh_domain_parameters, encode_dh_domain_parameters, encode_dh_public_key, ) from . import TestCase, requires, FIXME class DHTests(TestCase): @requires(Mechanism.DH_PKCS_KEY_PAIR_GEN, Mechanism.DH_PKCS_DERIVE) @FIXME.opencryptoki # AttributeValueInvalid when generating keypair def test_derive_key(self): # Alice and Bob each create a Diffie-Hellman keypair from the # publicly available DH parameters # # E.g. RFC 3526, RFC 5114 or openssl dhparam -C 2236 prime = [ 0x0F,0x52,0xE5,0x24,0xF5,0xFA,0x9D,0xDC,0xC6,0xAB,0xE6,0x04, # noqa 0xE4,0x20,0x89,0x8A,0xB4,0xBF,0x27,0xB5,0x4A,0x95,0x57,0xA1, # noqa 0x06,0xE7,0x30,0x73,0x83,0x5E,0xC9,0x23,0x11,0xED,0x42,0x45, # noqa 0xAC,0x49,0xD3,0xE3,0xF3,0x34,0x73,0xC5,0x7D,0x00,0x3C,0x86, # noqa 0x63,0x74,0xE0,0x75,0x97,0x84,0x1D,0x0B,0x11,0xDA,0x04,0xD0, # noqa 0xFE,0x4F,0xB0,0x37,0xDF,0x57,0x22,0x2E,0x96,0x42,0xE0,0x7C, # noqa 0xD7,0x5E,0x46,0x29,0xAF,0xB1,0xF4,0x81,0xAF,0xFC,0x9A,0xEF, # noqa 0xFA,0x89,0x9E,0x0A,0xFB,0x16,0xE3,0x8F,0x01,0xA2,0xC8,0xDD, # noqa 0xB4,0x47,0x12,0xF8,0x29,0x09,0x13,0x6E,0x9D,0xA8,0xF9,0x5D, # noqa 0x08,0x00,0x3A,0x8C,0xA7,0xFF,0x6C,0xCF,0xE3,0x7C,0x3B,0x6B, # noqa 0xB4,0x26,0xCC,0xDA,0x89,0x93,0x01,0x73,0xA8,0x55,0x3E,0x5B, # noqa 0x77,0x25,0x8F,0x27,0xA3,0xF1,0xBF,0x7A,0x73,0x1F,0x85,0x96, # noqa 0x0C,0x45,0x14,0xC1,0x06,0xB7,0x1C,0x75,0xAA,0x10,0xBC,0x86, # noqa 0x98,0x75,0x44,0x70,0xD1,0x0F,0x20,0xF4,0xAC,0x4C,0xB3,0x88, # noqa 0x16,0x1C,0x7E,0xA3,0x27,0xE4,0xAD,0xE1,0xA1,0x85,0x4F,0x1A, # noqa 0x22,0x0D,0x05,0x42,0x73,0x69,0x45,0xC9,0x2F,0xF7,0xC2,0x48, # noqa 0xE3,0xCE,0x9D,0x74,0x58,0x53,0xE7,0xA7,0x82,0x18,0xD9,0x3D, # noqa 0xAF,0xAB,0x40,0x9F,0xAA,0x4C,0x78,0x0A,0xC3,0x24,0x2D,0xDB, # noqa 0x12,0xA9,0x54,0xE5,0x47,0x87,0xAC,0x52,0xFE,0xE8,0x3D,0x0B, # noqa 0x56,0xED,0x9C,0x9F,0xFF,0x39,0xE5,0xE5,0xBF,0x62,0x32,0x42, # noqa 0x08,0xAE,0x6A,0xED,0x88,0x0E,0xB3,0x1A,0x4C,0xD3,0x08,0xE4, # noqa 0xC4,0xAA,0x2C,0xCC,0xB1,0x37,0xA5,0xC1,0xA9,0x64,0x7E,0xEB, # noqa 0xF9,0xD3,0xF5,0x15,0x28,0xFE,0x2E,0xE2,0x7F,0xFE,0xD9,0xB9, # noqa 0x38,0x42,0x57,0x03, # noqa ] parameters = self.session.create_domain_parameters(KeyType.DH, { Attribute.PRIME: prime, Attribute.BASE: [0x2], }, local=True) # Alice generate a keypair alice_public, alice_private = parameters.generate_keypair() alice_value = alice_public[Attribute.VALUE] # Bob generates a keypair bob_public, bob_private = parameters.generate_keypair() bob_value = bob_public[Attribute.VALUE] self.assertNotEqual(alice_value, bob_value) # Alice and Bob exchange values and an IV ... iv = self.session.generate_random(128) alice_session = alice_private.derive_key( KeyType.AES, 128, mechanism_param=bob_value, template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) bob_session = bob_private.derive_key( KeyType.AES, 128, mechanism_param=alice_value, template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) self.assertEqual(alice_session[Attribute.VALUE], bob_session[Attribute.VALUE]) crypttext = alice_session.encrypt('HI BOB!', mechanism_param=iv) plaintext = bob_session.decrypt(crypttext, mechanism_param=iv) self.assertEqual(plaintext, b'HI BOB!') def test_load_params(self): # This is RFC5114 #2 PARAMS = base64.b64decode(""" MIICKQKCAQEArRB+HpEjqdDWYPqnlVnFH6INZOVoO5/RtUsVl7YdCnXm+hQd+VpW 26+aPEB7od8V6z1oijCcGA4d5rhaEnSgpm0/gVKtasISkDfJ7e/aTfjZHo/vVbc5 S3rVt9C2wSIHyfmNEe002/bGugssi7wnvmoA4KC5xJcIs7+KMXCRiDaBKGEwvImF 2xYC5xRBXZMwJ4Jzx94x79xzEPcSH9WgdBWYfZrcCkhtzfk6zEQyg4cxXXXhmMZB pIDNhqG55YfovmDmnMkosrnFIXLkEwQumyPxCw4W55djybU9z0uoCinj+3PBa451 uX7zY+L/ox9xz53lOE5xuBwKxN/+DBDmTwKCAQEArEAy708tmuOd8wtcj/2sUGze vnuJmYyvdIZqCM/k/+OmgkpOELmm8N2SHwGnDEr6q3OddwDCn1LFfbF8YgqGUr5e kAGo1mrXwXZpEBmZAkr00CcnWsE0i7inYtBSG8mK4kcVBCLqHtQJk51U2nRgzbX2 xrJQcXy+8YDrNBGOmNEZUppF1vg0Vm4wJeMWozDvu3eobwwasVsFGuPUKMj4rLcK gTcVC47rEOGD7dGZY93Z4mPkdwWJ72qiHn9fL/OBtTnM40CdE81Wavu0jWwBkYHh vP6UswJp7f5y/ptqpL17Wg8ccc//TBnEGOH27AF5gbwIfypwZbOEuJDTGR8r+gId AIAcDTTFjZP+mXF3EB+AU1pHOM68vziambNjces= """) params = self.session.create_domain_parameters( KeyType.DH, decode_dh_domain_parameters(PARAMS), local=True) self.assertIsInstance(params, DomainParameters) self.assertEqual(params[Attribute.PRIME][:4], b'\xAD\x10\x7E\x1E') @requires(Mechanism.DH_PKCS_PARAMETER_GEN, Mechanism.DH_PKCS_KEY_PAIR_GEN) def test_generate_params(self): params = self.session.generate_domain_parameters(KeyType.DH, 512) self.assertIsInstance(params, DomainParameters) self.assertEqual(params[Attribute.PRIME_BITS], 512) self.assertEqual(len(params[Attribute.PRIME]) * 8, 512) encode_dh_domain_parameters(params) # Test encoding the public key public, _ = params.generate_keypair() encode_dh_public_key(public) python-pkcs11-0.7.0/tests/test_aes.py0000664000372000037200000000766513717606207020353 0ustar travistravis00000000000000""" PKCS#11 AES Secret Keys """ import pkcs11 from pkcs11 import Mechanism from . import TestCase, requires, FIXME class AESTests(TestCase): @requires(Mechanism.AES_KEY_GEN) def setUp(self): super().setUp() self.key = self.session.generate_key(pkcs11.KeyType.AES, 128) @requires(Mechanism.AES_CBC_PAD) def test_encrypt(self): data = b'INPUT DATA' iv = b'0' * 16 crypttext = self.key.encrypt(data, mechanism_param=iv) self.assertIsInstance(crypttext, bytes) self.assertNotEqual(data, crypttext) # We should be aligned to the block size self.assertEqual(len(crypttext), 16) # Ensure we didn't just get 16 nulls self.assertFalse(all(c == '\0' for c in crypttext)) text = self.key.decrypt(crypttext, mechanism_param=iv) self.assertEqual(data, text) @requires(Mechanism.AES_CBC_PAD) def test_encrypt_stream(self): data = ( b'I' * 16, b'N' * 16, b'P' * 16, b'U' * 16, b'T' * 10, # don't align to the blocksize ) iv = b'0' * 16 cryptblocks = list(self.key.encrypt(data, mechanism_param=iv)) self.assertEqual(len(cryptblocks), len(data) + 1) crypttext = b''.join(cryptblocks) self.assertNotEqual(b''.join(data), crypttext) # We should be aligned to the block size self.assertEqual(len(crypttext) % 16, 0) # Ensure we didn't just get 16 nulls self.assertFalse(all(c == '\0' for c in crypttext)) text = b''.join(self.key.decrypt(cryptblocks, mechanism_param=iv)) self.assertEqual(b''.join(data), text) @requires(Mechanism.AES_CBC_PAD) def test_encrypt_whacky_sizes(self): data = [ (char * ord(char)).encode('utf-8') for char in 'HELLO WORLD' ] iv = b'0' * 16 cryptblocks = list(self.key.encrypt(data, mechanism_param=iv)) textblocks = list(self.key.decrypt(cryptblocks, mechanism_param=iv)) self.assertEqual(b''.join(data), b''.join(textblocks)) @requires(Mechanism.AES_CBC_PAD) def test_encrypt_big_string(self): data = b'HELLO WORLD' * 1024 iv = self.session.generate_random(128) crypttext = self.key.encrypt(data, mechanism_param=iv) text = self.key.decrypt(crypttext, mechanism_param=iv) self.assertEqual(text, data) @requires(Mechanism.AES_MAC) def test_sign(self): data = b'HELLO WORLD' signature = self.key.sign(data) self.assertIsNotNone(signature) self.assertIsInstance(signature, bytes) self.assertTrue(self.key.verify(data, signature)) self.assertFalse(self.key.verify(data, b'1234')) @requires(Mechanism.AES_MAC) def test_sign_stream(self): data = ( b'I' * 16, b'N' * 16, b'P' * 16, b'U' * 16, b'T' * 10, # don't align to the blocksize ) signature = self.key.sign(data) self.assertIsNotNone(signature) self.assertIsInstance(signature, bytes) self.assertTrue(self.key.verify(data, signature)) @requires(Mechanism.AES_KEY_WRAP) @FIXME.opencryptoki # can't set key attributes def test_wrap(self): key = self.session.generate_key(pkcs11.KeyType.AES, 128, template={ pkcs11.Attribute.EXTRACTABLE: True, pkcs11.Attribute.SENSITIVE: False, }) data = self.key.wrap_key(key) key2 = self.key.unwrap_key(pkcs11.ObjectClass.SECRET_KEY, pkcs11.KeyType.AES, data, template={ pkcs11.Attribute.EXTRACTABLE: True, pkcs11.Attribute.SENSITIVE: False, }) self.assertEqual(key[pkcs11.Attribute.VALUE], key2[pkcs11.Attribute.VALUE]) python-pkcs11-0.7.0/tests/test_public_key_external.py0000664000372000037200000001422213717606207023616 0ustar travistravis00000000000000from pkcs11 import KeyType, ObjectClass, Mechanism, Attribute, KDF from pkcs11.util.rsa import encode_rsa_public_key from pkcs11.util.ec import ( decode_ec_public_key, encode_ec_public_key, encode_ecdsa_signature, encode_named_curve_parameters, ) from . import TestCase, requires, Is class ExternalPublicKeyTests(TestCase): @requires(Mechanism.RSA_PKCS) def test_rsa(self): # A key we generated earlier self.session.generate_keypair(KeyType.RSA, 1024) pub = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) pub = encode_rsa_public_key(pub) from oscrypto.asymmetric import load_public_key, rsa_pkcs1v15_encrypt pub = load_public_key(pub) crypttext = rsa_pkcs1v15_encrypt(pub, b'Data to encrypt') priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) plaintext = priv.decrypt(crypttext, mechanism=Mechanism.RSA_PKCS) self.assertEqual(plaintext, b'Data to encrypt') @requires(Mechanism.ECDSA_SHA1) def test_ecdsa(self): # A key we generated earlier self.session.create_domain_parameters(KeyType.EC, { Attribute.EC_PARAMS: encode_named_curve_parameters('secp256r1'), }, local=True)\ .generate_keypair() priv = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PRIVATE_KEY) signature = priv.sign(b'Data to sign', mechanism=Mechanism.ECDSA_SHA1) # Encode as ASN.1 for OpenSSL signature = encode_ecdsa_signature(signature) from oscrypto.asymmetric import load_public_key, ecdsa_verify pub = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PUBLIC_KEY) pub = load_public_key(encode_ec_public_key(pub)) ecdsa_verify(pub, signature, b'Data to sign', 'sha1') @requires(Mechanism.ECDH1_DERIVE) def test_ecdh(self): # A key we generated earlier self.session.create_domain_parameters(KeyType.EC, { Attribute.EC_PARAMS: encode_named_curve_parameters('secp256r1'), }, local=True)\ .generate_keypair() # Retrieve our keypair, with our public key encoded for interchange alice_priv = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PRIVATE_KEY) alice_pub = self.session.get_key(key_type=KeyType.EC, object_class=ObjectClass.PUBLIC_KEY) alice_pub = encode_ec_public_key(alice_pub) from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.serialization import \ Encoding, PublicFormat, load_der_public_key # Bob generates a keypair, with their public key encoded for # interchange bob_priv = ec.generate_private_key(ec.SECP256R1, default_backend()) bob_pub = bob_priv.public_key().public_bytes( Encoding.DER, PublicFormat.SubjectPublicKeyInfo, ) # Bob converts Alice's key to internal format and generates their # shared key bob_shared_key = bob_priv.exchange( ec.ECDH(), load_der_public_key(alice_pub, default_backend()), ) key = alice_priv.derive_key( KeyType.GENERIC_SECRET, 256, mechanism_param=( KDF.NULL, None, # N.B. it seems like SoftHSMv2 requires an EC_POINT to be # DER-encoded, which is not what the spec says decode_ec_public_key(bob_pub, encode_ec_point=Is.softhsm2) [Attribute.EC_POINT], ), template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }, ) alice_shared_key = key[Attribute.VALUE] # We should have the same shared key self.assertEqual(bob_shared_key, alice_shared_key) @requires(Mechanism.RSA_PKCS) def test_terrible_hybrid_file_encryption_app(self): # Proof of concept code only! import io from oscrypto.asymmetric import load_public_key, rsa_pkcs1v15_encrypt from oscrypto.symmetric import ( aes_cbc_pkcs7_encrypt, aes_cbc_pkcs7_decrypt, ) # A key we generated earlier self.session.generate_keypair(KeyType.RSA, 1024) pub = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PUBLIC_KEY) pub = load_public_key(encode_rsa_public_key(pub)) key = self.session.generate_random(256) iv = self.session.generate_random(128) source = b'This is my amazing file' with io.BytesIO() as dest: # Write a 128-byte header containing our key and our IV # strictly speaking we don't need to keep the IV secure but # we may as well. # # FIXME: Because this is RSA 1.5, we should fill the rest of the # frame with nonsense self.assertEqual(dest.write(rsa_pkcs1v15_encrypt(pub, key + iv)), 128) _, ciphertext = aes_cbc_pkcs7_encrypt(key, source, iv) dest.write(ciphertext) # Time passes dest.seek(0) # Look up our private key priv = self.session.get_key(key_type=KeyType.RSA, object_class=ObjectClass.PRIVATE_KEY) # Read the header header = dest.read(priv.key_length // 8) header = priv.decrypt(header, mechanism=Mechanism.RSA_PKCS) # The first 32 bytes is our key key, header = header[:32], header[32:] # The next 16 bytes is the IV iv = header[:16] # We can ignore the rest plaintext = aes_cbc_pkcs7_decrypt(key, dest.read(), iv) self.assertEqual(source, plaintext) python-pkcs11-0.7.0/tests/test_ecc.py0000664000372000037200000001612613717606207020325 0ustar travistravis00000000000000""" PKCS#11 Elliptic Curve Cryptography. """ import base64 import pkcs11 from pkcs11 import Attribute, KeyType, KDF, Mechanism from pkcs11.util.ec import ( encode_named_curve_parameters, decode_ec_public_key, decode_ec_private_key, encode_ec_public_key, decode_ecdsa_signature, ) from . import TestCase, requires class ECCTests(TestCase): @requires(Mechanism.EC_KEY_PAIR_GEN, Mechanism.ECDSA) def test_sign_ecdsa(self): parameters = self.session.create_domain_parameters(KeyType.EC, { Attribute.EC_PARAMS: encode_named_curve_parameters('secp256r1') }, local=True) pub, priv = parameters.generate_keypair() mechanism = Mechanism.ECDSA data = b'HI BOB!' ecdsa = priv.sign(data, mechanism=mechanism) self.assertTrue(pub.verify(data, ecdsa, mechanism=mechanism)) @requires(Mechanism.EC_KEY_PAIR_GEN, Mechanism.ECDH1_DERIVE) def test_derive_key(self): # DER encoded EC params from OpenSSL # openssl ecparam -out ec_param.der -name prime192v1 ecparams = base64.b64decode(b'BggqhkjOPQMBAQ==') parameters = self.session.create_domain_parameters(KeyType.EC, { Attribute.EC_PARAMS: ecparams, }, local=True) alice_pub, alice_priv = parameters.generate_keypair() alice_value = alice_pub[Attribute.EC_POINT] bob_pub, bob_priv = parameters.generate_keypair() bob_value = bob_pub[Attribute.EC_POINT] self.assertNotEqual(alice_value, bob_value) alice_session = alice_priv.derive_key( KeyType.AES, 128, mechanism_param=(KDF.NULL, None, bob_value)) bob_session = bob_priv.derive_key( KeyType.AES, 128, mechanism_param=(KDF.NULL, None, alice_value)) iv = self.session.generate_random(128) crypttext = alice_session.encrypt('HI BOB!', mechanism_param=iv) plaintext = bob_session.decrypt(crypttext, mechanism_param=iv) self.assertEqual(plaintext, b'HI BOB!') @requires(Mechanism.ECDSA) def test_import_key_params(self): der = base64.b64decode(""" MIICXDCCAc8GByqGSM49AgEwggHCAgEBME0GByqGSM49AQECQgH///////////// //////////////////////////////////////////////////////////////// /////////zCBngRCAf////////////////////////////////////////////// ///////////////////////////////////////8BEFRlT65YY4cmh+SmiGgtoVA 7qLacluZsxXzuLSJkY7xCeFWGTlR7H6TexZSwL07sb8HNXPfiD0sNPHvRR/Ua1A/ AAMVANCeiAApHLhTlsxnFzkyhKqg2mS6BIGFBADGhY4GtwQE6c2ePstmI5W0Qpxk gTkFP7Uh+CivYGtNPbqhS1537+dZKP4dwSei/6jeM0izwYVqQpv5fn4xwuW9ZgEY OSlqeJo7wARcil+0LH0b2Zj1RElXm0RoF6+9Fyc+ZiyX7nKZXvQmQMVQuQE/rQdh NTxwhqJywkCIvpR2n9FmUAJCAf////////////////////////////////////// ////+lGGh4O/L5Zrf8wBSPcJpdA7tcm4iZxHrrtvtx6ROGQJAgEBA4GGAAQBMLgt gTFBGr0f7YrWwZsCPpLxaUQvUKvz2C6ghiFmxc2EzBgxDY+ywnmG4T++EVZhJHTP eIOnVRcHXXivkRe+YMQBbH/fZyqfCe41vIl39bwhqli839AAj/WoxXZuilpKaXBp vGbx2380UIhrec1jFjItOOg/Xp9dOecjQZK7Z0wVq1U= """) key = self.session.create_object(decode_ec_public_key(der)) self.assertIsInstance(key, pkcs11.PublicKey) # We should get back to identity self.assertEqual(encode_ec_public_key(key), der) @requires(Mechanism.ECDSA_SHA1) def test_import_key_named_curve(self): der = base64.b64decode(""" MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEa6Q5Hs+j71J1lc+VziafH+uL6603 R8gTAphQD0iLG9Q9RgAvDQdFFpzkvXI+mEGVNRMmT/BA1OtficHcAXTdXA== """) key = self.session.create_object(decode_ec_public_key(der)) self.assertIsInstance(key, pkcs11.PublicKey) # Something signed with OpenSSL signature = base64.b64decode(""" MEYCIQD1nDlli+uLuGX3eobKJe7PsRYkYJ4F15bjqbbB+MHewwIhAPGFRwyuFOvH zuj+sxXwk1CsDWN7AXbmHufOlOarXpiq """) signature = decode_ecdsa_signature(signature) self.assertTrue(key.verify(b'Data to sign', signature, mechanism=Mechanism.ECDSA_SHA1)) # We should get back to identity self.assertEqual(encode_ec_public_key(key), der) @requires(Mechanism.ECDSA) def test_import_key_pair(self): priv = base64.b64decode(""" MIICnAIBAQRB9JsyE7khj/d2jm5RkE9T2DKgr/y3gn4Ju+8oWfdIpurNKM4hh3Oo 0T+ilc0BEy/SfJ5iqUxU5TocdFRpOUzfUIKgggHGMIIBwgIBATBNBgcqhkjOPQEB AkIB//////////////////////////////////////////////////////////// //////////////////////////8wgZ4EQgH///////////////////////////// /////////////////////////////////////////////////////////ARBUZU+ uWGOHJofkpohoLaFQO6i2nJbmbMV87i0iZGO8QnhVhk5Uex+k3sWUsC9O7G/BzVz 34g9LDTx70Uf1GtQPwADFQDQnogAKRy4U5bMZxc5MoSqoNpkugSBhQQAxoWOBrcE BOnNnj7LZiOVtEKcZIE5BT+1Ifgor2BrTT26oUted+/nWSj+HcEnov+o3jNIs8GF akKb+X5+McLlvWYBGDkpaniaO8AEXIpftCx9G9mY9URJV5tEaBevvRcnPmYsl+5y mV70JkDFULkBP60HYTU8cIaicsJAiL6Udp/RZlACQgH///////////////////// //////////////////////pRhoeDvy+Wa3/MAUj3CaXQO7XJuImcR667b7cekThk CQIBAaGBiQOBhgAEATC4LYExQRq9H+2K1sGbAj6S8WlEL1Cr89guoIYhZsXNhMwY MQ2PssJ5huE/vhFWYSR0z3iDp1UXB114r5EXvmDEAWx/32cqnwnuNbyJd/W8IapY vN/QAI/1qMV2bopaSmlwabxm8dt/NFCIa3nNYxYyLTjoP16fXTnnI0GSu2dMFatV """) priv = self.session.create_object(decode_ec_private_key(priv)) pub = base64.b64decode(""" MIICXDCCAc8GByqGSM49AgEwggHCAgEBME0GByqGSM49AQECQgH///////////// //////////////////////////////////////////////////////////////// /////////zCBngRCAf////////////////////////////////////////////// ///////////////////////////////////////8BEFRlT65YY4cmh+SmiGgtoVA 7qLacluZsxXzuLSJkY7xCeFWGTlR7H6TexZSwL07sb8HNXPfiD0sNPHvRR/Ua1A/ AAMVANCeiAApHLhTlsxnFzkyhKqg2mS6BIGFBADGhY4GtwQE6c2ePstmI5W0Qpxk gTkFP7Uh+CivYGtNPbqhS1537+dZKP4dwSei/6jeM0izwYVqQpv5fn4xwuW9ZgEY OSlqeJo7wARcil+0LH0b2Zj1RElXm0RoF6+9Fyc+ZiyX7nKZXvQmQMVQuQE/rQdh NTxwhqJywkCIvpR2n9FmUAJCAf////////////////////////////////////// ////+lGGh4O/L5Zrf8wBSPcJpdA7tcm4iZxHrrtvtx6ROGQJAgEBA4GGAAQBMLgt gTFBGr0f7YrWwZsCPpLxaUQvUKvz2C6ghiFmxc2EzBgxDY+ywnmG4T++EVZhJHTP eIOnVRcHXXivkRe+YMQBbH/fZyqfCe41vIl39bwhqli839AAj/WoxXZuilpKaXBp vGbx2380UIhrec1jFjItOOg/Xp9dOecjQZK7Z0wVq1U= """) pub = self.session.create_object(decode_ec_public_key(pub)) signature = priv.sign(b'Example', mechanism=Mechanism.ECDSA) self.assertTrue(pub.verify(b'Example', signature, mechanism=Mechanism.ECDSA)) @requires(Mechanism.EC_EDWARDS_KEY_PAIR_GEN, Mechanism.EDDSA) def test_sign_eddsa(self): parameters = self.session.create_domain_parameters(KeyType.EC, { # use "Ed25519" once https://github.com/wbond/asn1crypto/pull/134 # is merged Attribute.EC_PARAMS: encode_named_curve_parameters('1.3.101.112') }, local=True) pub, priv = parameters.generate_keypair() mechanism = Mechanism.EDDSA data = b'HI BOB!' eddsa = priv.sign(data, mechanism=mechanism) self.assertTrue(pub.verify(data, eddsa, mechanism=mechanism)) python-pkcs11-0.7.0/tests/test_threading.py0000664000372000037200000000243013717606207021531 0ustar travistravis00000000000000""" PKCS#11 Thread Safety tests Even though you have a session construct it turns out the expectation of PKCS#11 is that you have a single session per process. """ import threading import pkcs11 from . import TestCase, Not, requires @Not.nfast # Deadlocks nfast ... something wrong with threading? class ThreadingTests(TestCase): @requires(pkcs11.Mechanism.AES_KEY_GEN, pkcs11.Mechanism.AES_CBC_PAD) def test_concurrency(self): # Multiplexing a session between processes self.session.generate_key(pkcs11.KeyType.AES, 128, label='LOOK ME UP') test_passed = [True] def thread_work(): try: data = b'1234' * 1024 * 1024 # Multichunk files iv = self.session.generate_random(128) key = self.session.get_key(label='LOOK ME UP') self.assertIsNotNone(key.encrypt(data, mechanism_param=iv)) except pkcs11.PKCS11Error: test_passed[0] = False raise threads = [ threading.Thread(target=thread_work) for _ in range(10) ] for thread in threads: thread.start() # join each thread for thread in threads: thread.join() self.assertTrue(test_passed[0]) python-pkcs11-0.7.0/tests/test_sessions.py0000664000372000037200000001425513717606207021442 0ustar travistravis00000000000000""" PKCS#11 Sessions """ import pkcs11 from . import TestCase, TOKEN_PIN, TOKEN_SO_PIN, Not, Only, requires, FIXME class SessionTests(TestCase): with_session = False @Not.nfast # Login is required @Not.opencryptoki def test_open_session(self): with self.token.open() as session: self.assertIsInstance(session, pkcs11.Session) def test_open_session_and_login_user(self): with self.token.open(user_pin=TOKEN_PIN) as session: self.assertIsInstance(session, pkcs11.Session) @Only.softhsm2 # We don't have credentials to do this for other platforms def test_open_session_and_login_so(self): with self.token.open(rw=True, so_pin=TOKEN_SO_PIN) as session: self.assertIsInstance(session, pkcs11.Session) @requires(pkcs11.Mechanism.AES_KEY_GEN) def test_generate_key(self): with self.token.open(user_pin=TOKEN_PIN) as session: key = session.generate_key(pkcs11.KeyType.AES, 128) self.assertIsInstance(key, pkcs11.Object) self.assertIsInstance(key, pkcs11.SecretKey) self.assertIsInstance(key, pkcs11.EncryptMixin) self.assertIs(key.object_class, pkcs11.ObjectClass.SECRET_KEY) # Test GetAttribute self.assertIs(key[pkcs11.Attribute.CLASS], pkcs11.ObjectClass.SECRET_KEY) self.assertEqual(key[pkcs11.Attribute.TOKEN], False) self.assertEqual(key[pkcs11.Attribute.LOCAL], True) self.assertEqual(key[pkcs11.Attribute.MODIFIABLE], True) self.assertEqual(key[pkcs11.Attribute.LABEL], '') # Test SetAttribute key[pkcs11.Attribute.LABEL] = "DEMO" self.assertEqual(key[pkcs11.Attribute.LABEL], "DEMO") # Create another key with no capabilities key = session.generate_key(pkcs11.KeyType.AES, 128, label='MY KEY', id=b'\1\2\3\4', capabilities=0) self.assertIsInstance(key, pkcs11.Object) self.assertIsInstance(key, pkcs11.SecretKey) self.assertNotIsInstance(key, pkcs11.EncryptMixin) self.assertEqual(key.label, 'MY KEY') @requires(pkcs11.Mechanism.RSA_PKCS_KEY_PAIR_GEN, pkcs11.Mechanism.RSA_PKCS) def test_generate_keypair(self): with self.token.open(user_pin=TOKEN_PIN) as session: pub, priv = session.generate_keypair( pkcs11.KeyType.RSA, 1024) self.assertIsInstance(pub, pkcs11.PublicKey) self.assertIsInstance(priv, pkcs11.PrivateKey) data = b'HELLO WORLD' crypttext = pub.encrypt(data, mechanism=pkcs11.Mechanism.RSA_PKCS) self.assertNotEqual(data, crypttext) text = priv.decrypt(crypttext, mechanism=pkcs11.Mechanism.RSA_PKCS) self.assertEqual(data, text) @requires(pkcs11.Mechanism.AES_KEY_GEN) def test_get_objects(self): with self.token.open(user_pin=TOKEN_PIN) as session: key = session.generate_key(pkcs11.KeyType.AES, 128, label='SAMPLE KEY') search = list(session.get_objects({ pkcs11.Attribute.LABEL: 'SAMPLE KEY', })) self.assertEqual(len(search), 1) self.assertEqual(key, search[0]) @FIXME.opencryptoki def test_create_object(self): with self.token.open(user_pin=TOKEN_PIN) as session: key = session.create_object({ pkcs11.Attribute.CLASS: pkcs11.ObjectClass.SECRET_KEY, pkcs11.Attribute.KEY_TYPE: pkcs11.KeyType.AES, pkcs11.Attribute.VALUE: b'1' * 16, }) self.assertIsInstance(key, pkcs11.SecretKey) self.assertEqual(key.key_length, 128) @Not.nfast # nFast won't destroy objects def test_destroy_object(self): with self.token.open(user_pin=TOKEN_PIN) as session: key = session.generate_key(pkcs11.KeyType.AES, 128, label='SAMPLE KEY') key.destroy() self.assertEqual(list(session.get_objects()), []) @Only.softhsm2 def test_copy_object(self): with self.token.open(user_pin=TOKEN_PIN) as session: key = session.generate_key(pkcs11.KeyType.AES, 128, label='SAMPLE KEY') new = key.copy({ pkcs11.Attribute.LABEL: 'SOMETHING ELSE', }) self.assertEqual(set(session.get_objects()), {key, new}) @requires(pkcs11.Mechanism.AES_KEY_GEN) def test_get_key(self): with self.token.open(user_pin=TOKEN_PIN) as session: session.generate_key(pkcs11.KeyType.AES, 128, label='SAMPLE KEY') key = session.get_key(label='SAMPLE KEY',) self.assertIsInstance(key, pkcs11.SecretKey) key.encrypt(b'test', mechanism_param=b'IV' * 8) def test_get_key_not_found(self): with self.token.open(user_pin=TOKEN_PIN) as session: with self.assertRaises(pkcs11.NoSuchKey): session.get_key(label='SAMPLE KEY') @requires(pkcs11.Mechanism.AES_KEY_GEN) def test_get_key_vague(self): with self.token.open(user_pin=TOKEN_PIN) as session: session.generate_key(pkcs11.KeyType.AES, 128, label='SAMPLE KEY') session.generate_key(pkcs11.KeyType.AES, 128, label='SAMPLE KEY 2') with self.assertRaises(pkcs11.MultipleObjectsReturned): session.get_key(key_type=pkcs11.KeyType.AES) @Not.nfast # Not supported @Not.opencryptoki # Not supported def test_seed_random(self): with self.token.open() as session: session.seed_random(b'12345678') def test_generate_random(self): with self.token.open(user_pin=TOKEN_PIN) as session: random = session.generate_random(16 * 8) self.assertEqual(len(random), 16) # Ensure we didn't get 16 bytes of zeros self.assertTrue(all(c != '\0' for c in random)) python-pkcs11-0.7.0/tests/test_digest.py0000664000372000037200000000412713717606207021050 0ustar travistravis00000000000000""" PKCS#11 Digests """ import hashlib from pkcs11 import Mechanism, KeyType, Attribute from . import TestCase, Not, requires class DigestTests(TestCase): @requires(Mechanism.SHA256) def test_digest(self): data = 'THIS IS SOME DATA TO DIGEST' digest = self.session.digest(data, mechanism=Mechanism.SHA256) self.assertEqual(digest, hashlib.sha256(data.encode('utf-8')).digest()) @requires(Mechanism.SHA256) def test_digest_generator(self): data = ( b'This is ', b'some data ', b'to digest.', ) digest = self.session.digest(data, mechanism=Mechanism.SHA256) m = hashlib.sha256() for d in data: m.update(d) self.assertEqual(digest, m.digest()) @requires(Mechanism.AES_KEY_GEN, Mechanism.SHA256) @Not.nfast # nFast can't digest keys def test_digest_key(self): key = self.session.generate_key(KeyType.AES, 128, template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) digest = self.session.digest(key, mechanism=Mechanism.SHA256) self.assertEqual(digest, hashlib.sha256(key[Attribute.VALUE]).digest()) @requires(Mechanism.AES_KEY_GEN, Mechanism.SHA256) @Not.nfast # nFast can't digest keys def test_digest_key_data(self): key = self.session.generate_key(KeyType.AES, 128, template={ Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True, }) data = ( b'Some data', key, ) digest = self.session.digest(data, mechanism=Mechanism.SHA256) m = hashlib.sha256() m.update(data[0]) m.update(data[1][Attribute.VALUE]) self.assertEqual(digest, m.digest()) python-pkcs11-0.7.0/tests/test_des.py0000664000372000037200000000237213717606207020344 0ustar travistravis00000000000000""" PKCS#11 DES Secret Keys """ import pkcs11 from pkcs11 import KeyType, Mechanism from . import TestCase, requires class DESTests(TestCase): @requires(Mechanism.DES2_KEY_GEN) def test_generate_des2_key(self): key = self.session.generate_key(KeyType.DES2) self.assertIsInstance(key, pkcs11.SecretKey) @requires(Mechanism.DES3_KEY_GEN) def test_generate_des3_key(self): key = self.session.generate_key(KeyType.DES3) self.assertIsInstance(key, pkcs11.SecretKey) @requires(Mechanism.DES2_KEY_GEN, Mechanism.DES3_CBC_PAD) def test_encrypt_des2(self): key = self.session.generate_key(KeyType.DES2) iv = self.session.generate_random(64) crypttext = key.encrypt('PLAIN TEXT_', mechanism_param=iv) plaintext = key.decrypt(crypttext, mechanism_param=iv) self.assertEqual(plaintext, b'PLAIN TEXT_') @requires(Mechanism.DES3_KEY_GEN, Mechanism.DES3_CBC_PAD) def test_encrypt_des3(self): key = self.session.generate_key(KeyType.DES3) iv = self.session.generate_random(64) crypttext = key.encrypt('PLAIN TEXT_', mechanism_param=iv) plaintext = key.decrypt(crypttext, mechanism_param=iv) self.assertEqual(plaintext, b'PLAIN TEXT_') python-pkcs11-0.7.0/tests/test_x509.py0000664000372000037200000002446313717606207020303 0ustar travistravis00000000000000""" X.509 Certificate Tests """ import base64 import subprocess import datetime from asn1crypto import pem from asn1crypto.x509 import Certificate, TbsCertificate, Time, Name from asn1crypto.keys import RSAPublicKey from asn1crypto.csr import CertificationRequest, CertificationRequestInfo import pkcs11 from pkcs11.util.rsa import encode_rsa_public_key from pkcs11.util.dsa import decode_dsa_signature from pkcs11.util.ec import decode_ecdsa_signature from pkcs11.util.x509 import decode_x509_certificate, decode_x509_public_key from pkcs11 import ( Attribute, KeyType, Mechanism, ) from . import TestCase, Not, Only, requires, OPENSSL # X.509 self-signed certificate (generated with OpenSSL) # openssl req -x509 \ # -newkey rsa:512 \ # -keyout key.pem \ # -out cert.pem \ # -days 365 \ # -nodes _, _, CERT = pem.unarmor(b""" -----BEGIN CERTIFICATE----- MIICKzCCAdWgAwIBAgIJAK3BO9rnLZd9MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTcwNjAyMDI0ODMyWhcNMTgwNjAyMDI0ODMyWjBF MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK5z DJiUDIutdWY8sT2O2ABKh5nmWjc4uEjNj/i5ZLQ4YlRmDL4e2vWs/GOFLVtTJKj6 rh4fj65Xo6X/5R/y+U8CAwEAAaOBpzCBpDAdBgNVHQ4EFgQU+cG240Pzz0y6igtm hnk1+1KFv6gwdQYDVR0jBG4wbIAU+cG240Pzz0y6igtmhnk1+1KFv6ihSaRHMEUx CzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRl cm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCtwTva5y2XfTAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA0EAOdvMKLrIFOYF3aVLGharY196heO0fndm39sZAXJ4PItx n28DytHEdAoltksfJ2Ds3XAjQqcpI5eBbhIoN9Ckxg== -----END CERTIFICATE----- """) class X509Tests(TestCase): def test_import_ca_certificate_easy(self): cert = self.session.create_object(decode_x509_certificate(CERT)) self.assertIsInstance(cert, pkcs11.Certificate) @Not.nfast @Not.opencryptoki def test_import_ca_certificate(self): cert = self.session.create_object( decode_x509_certificate(CERT, extended_set=True)) self.assertIsInstance(cert, pkcs11.Certificate) self.assertEqual(cert[Attribute.HASH_OF_ISSUER_PUBLIC_KEY], b'\xf9\xc1\xb6\xe3\x43\xf3\xcf\x4c\xba\x8a' b'\x0b\x66\x86\x79\x35\xfb\x52\x85\xbf\xa8') # Cert is self signed self.assertEqual(cert[Attribute.HASH_OF_SUBJECT_PUBLIC_KEY], b'\xf9\xc1\xb6\xe3\x43\xf3\xcf\x4c\xba\x8a' b'\x0b\x66\x86\x79\x35\xfb\x52\x85\xbf\xa8') @requires(Mechanism.SHA1_RSA_PKCS) def test_verify_certificate_rsa(self): # Warning: proof of concept code only! x509 = Certificate.load(CERT) key = self.session.create_object(decode_x509_public_key(CERT)) self.assertIsInstance(key, pkcs11.PublicKey) value = x509['tbs_certificate'].dump() signature = x509.signature assert x509.signature_algo == 'rsassa_pkcs1v15' assert x509.hash_algo == 'sha1' self.assertTrue(key.verify(value, signature, mechanism=Mechanism.SHA1_RSA_PKCS)) @requires(Mechanism.DSA_SHA1) def test_verify_certificate_dsa(self): # Warning: proof of concept code only! CERT = base64.b64decode(""" MIIDbjCCAy6gAwIBAgIJAKPBInGiPjXNMAkGByqGSM44BAMwRTELMAkGA1UEBhMC QVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdp dHMgUHR5IEx0ZDAeFw0xNzA3MDMxMjI1MTBaFw0xOTA3MDMxMjI1MTBaMEUxCzAJ BgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5l dCBXaWRnaXRzIFB0eSBMdGQwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA7U0AshA/ 4MXQ3MHykoeotEoPc+OXFMJ2PHzKfbFD80UC5bloxC9kp908GG3emdqbJuCTfVUD sex1vEgMj1sEwilBow954zMqncu5lLBIGZKjT6tloW8sFt50sE0l+YnBvAiw9uoL 9lBOZLKh87zWPZUuORm8lWhZEwjUnZ+3S5ECFQCNJGd68RpctgkA1kDp33NhQhev lQKBgQCQ6uYkvNpHMtXwyGII4JyOyStbteHjHdKfJfLNRyIEEq/E4e3Do6NGIr26 Z7u9iBsA5/aU6gKSBrYprxY1hdR4gTRBNzSUDEzf7IX3bfRIbBhjlNBSBba5Fs0z /kszZbZ8XYGVxs92aWFk/1JIZ0wnToC794+juq72/TvrtvxdowOBhAACgYAjoknQ kRD0+x3GkbngQCU+VNspZuXboB22CU3bDGVAVhmI5N02M8NmeuN7SqqYZAlw01Ju rzBF7i9VW4qxBaWszMCwyozerSVjZ2JA/Qubb57v/p7F3FDHq7E33FZzgyhOimds rzXpVErCGJJ1oBGz5H5fvoKnQmfh0X8N/VHkZqOBpzCBpDAdBgNVHQ4EFgQUQayv usUnpvRgc9OtXGddqMiwm5cwdQYDVR0jBG4wbIAUQayvusUnpvRgc9OtXGddqMiw m5ehSaRHMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYD VQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCjwSJxoj41zTAMBgNVHRME BTADAQH/MAkGByqGSM44BAMDLwAwLAIUNE+zTuFe01v0BRTLarPtGK8ZHHcCFB9Y YAwtpblAgUEdGuoAtnoEQ2tc """) x509 = Certificate.load(CERT) key = self.session.create_object(decode_x509_public_key(CERT)) self.assertIsInstance(key, pkcs11.PublicKey) value = x509['tbs_certificate'].dump() assert x509.signature_algo == 'dsa' assert x509.hash_algo == 'sha1' signature = decode_dsa_signature(x509.signature) self.assertTrue(key.verify(value, signature, mechanism=Mechanism.DSA_SHA1)) @requires(Mechanism.ECDSA_SHA1) def test_verify_certificate_ecdsa(self): # Warning: proof of concept code only! CERT = base64.b64decode(""" MIIDGjCCAsKgAwIBAgIJAL+PbwiJUZB1MAkGByqGSM49BAEwRTELMAkGA1UEBhMC QVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdp dHMgUHR5IEx0ZDAeFw0xNzA3MDMxMTUxMTBaFw0xOTA3MDMxMTUxMTBaMEUxCzAJ BgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5l dCBXaWRnaXRzIFB0eSBMdGQwggFLMIIBAwYHKoZIzj0CATCB9wIBATAsBgcqhkjO PQEBAiEA/////wAAAAEAAAAAAAAAAAAAAAD///////////////8wWwQg/////wAA AAEAAAAAAAAAAAAAAAD///////////////wEIFrGNdiqOpPns+u9VXaYhrxlHQaw zFOw9jvOPD4n0mBLAxUAxJ02CIbnBJNqZnjhE50mt4GffpAEQQRrF9Hy4SxCR/i8 5uVjpEDydwN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2 QGg3v1H1AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQEDQgAE royPJHkCQMq55egxmQxkFWqiz+yJx0MZP98is99SrkiK5UadFim3r3ZSt5kfh/cc Ccmy94BZCmihhGJ0F4eB2qOBpzCBpDAdBgNVHQ4EFgQURNXKlYGsAMItf4Ad8fkg Rg9ATqEwdQYDVR0jBG4wbIAURNXKlYGsAMItf4Ad8fkgRg9ATqGhSaRHMEUxCzAJ BgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5l dCBXaWRnaXRzIFB0eSBMdGSCCQC/j28IiVGQdTAMBgNVHRMEBTADAQH/MAkGByqG SM49BAEDRwAwRAIgAdJp/S9vSjS6EvRy/9zl5k2DBKGI52A3Ygsp1a96UicCIDul m/eL2OcGdNbzqzsC11alhemJX7Qt9GOcVqQwROIm """) x509 = Certificate.load(CERT) key = self.session.create_object(decode_x509_public_key(CERT)) self.assertIsInstance(key, pkcs11.PublicKey) value = x509['tbs_certificate'].dump() assert x509.signature_algo == 'ecdsa' assert x509.hash_algo == 'sha1' signature = decode_ecdsa_signature(x509.signature) self.assertTrue(key.verify(value, signature, mechanism=Mechanism.ECDSA_SHA1)) @Only.openssl @requires(Mechanism.RSA_PKCS_KEY_PAIR_GEN, Mechanism.SHA1_RSA_PKCS) def test_self_sign_certificate(self): # Warning: proof of concept code only! pub, priv = self.session.generate_keypair(KeyType.RSA, 1024) tbs = TbsCertificate({ 'version': 'v1', 'serial_number': 1, 'issuer': Name.build({ 'common_name': 'Test Certificate', }), 'subject': Name.build({ 'common_name': 'Test Certificate', }), 'signature': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'validity': { 'not_before': Time({ 'utc_time': datetime.datetime(2017, 1, 1, 0, 0), }), 'not_after': Time({ 'utc_time': datetime.datetime(2038, 12, 31, 23, 59), }), }, 'subject_public_key_info': { 'algorithm': { 'algorithm': 'rsa', 'parameters': None, }, 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)), } }) # Sign the TBS Certificate value = priv.sign(tbs.dump(), mechanism=Mechanism.SHA1_RSA_PKCS) cert = Certificate({ 'tbs_certificate': tbs, 'signature_algorithm': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'signature_value': value, }) # Pipe our certificate to OpenSSL to verify it with subprocess.Popen((OPENSSL, 'verify'), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) as proc: proc.stdin.write(pem.armor('CERTIFICATE', cert.dump())) proc.stdin.close() self.assertEqual(proc.wait(), 0) @Only.openssl @requires(Mechanism.RSA_PKCS_KEY_PAIR_GEN, Mechanism.SHA1_RSA_PKCS) def test_sign_csr(self): # Warning: proof of concept code only! pub, priv = self.session.generate_keypair(KeyType.RSA, 1024) info = CertificationRequestInfo({ 'version': 0, 'subject': Name.build({ 'common_name': 'Test Certificate', }), 'subject_pk_info': { 'algorithm': { 'algorithm': 'rsa', 'parameters': None, }, 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)), }, }) # Sign the CSR Info value = priv.sign(info.dump(), mechanism=Mechanism.SHA1_RSA_PKCS) csr = CertificationRequest({ 'certification_request_info': info, 'signature_algorithm': { 'algorithm': 'sha1_rsa', 'parameters': None, }, 'signature': value, }) # Pipe our CSR to OpenSSL to verify it with subprocess.Popen((OPENSSL, 'req', '-inform', 'der', '-noout', '-verify'), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL) as proc: proc.stdin.write(csr.dump()) proc.stdin.close() self.assertEqual(proc.wait(), 0) python-pkcs11-0.7.0/tests/test_dsa.py0000664000372000037200000000411613717606207020336 0ustar travistravis00000000000000""" PKCS#11 DSA Tests """ import base64 import pkcs11 from pkcs11 import KeyType, Attribute, Mechanism from pkcs11.util.dsa import ( encode_dsa_domain_parameters, decode_dsa_domain_parameters, ) from . import TestCase, requires, FIXME DHPARAMS = base64.b64decode(""" MIIBHwKBgQD8jXSat2sk+j0plaMn51AVYBWEyWee3ui3llRUckVceDILsjVdBs1tXCDhU7WC+VZZ u6ujBHZONiXcQTZ6P/jhnYlSyjEoBTf7GntlbjeASm63XYzTt4E5i7u1RI6TmEIRj6VTrM5m5DFP fDQ+fflAJzm0phT38gYE5xfe3mmCDQIVAMIMNr/4lufeH46EGKQXVnvtJBAZAoGBANxCIKAfh1/v MvI/2s7S1ESGuwvmvbFWpxW3gNXvyO2mWjfHC3sQrwm3qED0R71n9bIL6VqRK+tBEy6VkR+lKifA 8rPnZvADPNBhRLhgDc4JuwYinRJSUPd1iZxJCbumfscr3Fp1XuUnCcMRkWqWr7rGEUP+ht+AeXpo ouQbj2Vq """) class DSATests(TestCase): @requires(Mechanism.DSA_PARAMETER_GEN) @FIXME.nfast # returns Function Failed def test_generate_params(self): parameters = self.session.generate_domain_parameters(KeyType.DSA, 1024) self.assertIsInstance(parameters, pkcs11.DomainParameters) self.assertEqual(parameters[Attribute.PRIME_BITS], 1024) encode_dsa_domain_parameters(parameters) @requires(Mechanism.DSA_KEY_PAIR_GEN, Mechanism.DSA_SHA1) def test_generate_keypair_and_sign(self): dhparams = self.session.create_domain_parameters( KeyType.DSA, decode_dsa_domain_parameters(DHPARAMS), local=True) public, private = dhparams.generate_keypair() self.assertIsInstance(public, pkcs11.PublicKey) self.assertIsInstance(private, pkcs11.PrivateKey) self.assertEqual(len(public[Attribute.VALUE]), 1024 // 8) data = 'Message to sign' signature = private.sign(data, mechanism=Mechanism.DSA_SHA1) self.assertTrue(public.verify(data, signature, mechanism=Mechanism.DSA_SHA1)) @requires(Mechanism.DSA_PARAMETER_GEN, Mechanism.DSA_KEY_PAIR_GEN) @FIXME.nfast # returns Function Failed def test_generate_keypair_directly(self): public, private = self.session.generate_keypair(KeyType.DSA, 1024) self.assertEqual(len(public[Attribute.VALUE]), 1024 // 8) python-pkcs11-0.7.0/tests/__init__.py0000664000372000037200000001073013717606207020266 0ustar travistravis00000000000000""" PKCS#11 Tests The following environment variables will influence the behaviour of test cases: - PKCS11_MODULE, mandatory, points to the library/DLL to use for testing - PKCS11_TOKEN_LABEL, mandatory, contains the token label - PKCS11_TOKEN_PIN, optional (default is None), contains the PIN/passphrase of the token - PKCS11_TOKEN_SO_PIN, optional (default is same as PKCS11_TOKEN_PIN), security officer PIN - OPENSSL_PATH, optional, path to openssl executable (i.e. the folder that contains it) """ import os import shutil import unittest from functools import wraps from warnings import warn import pkcs11 try: LIB = os.environ['PKCS11_MODULE'] except KeyError: raise RuntimeError("Must define `PKCS11_MODULE' to run tests.") try: TOKEN = os.environ['PKCS11_TOKEN_LABEL'] except KeyError: raise RuntimeError("Must define `PKCS11_TOKEN_LABEL' to run tests.") TOKEN_PIN = os.environ.get('PKCS11_TOKEN_PIN') # Can be None if TOKEN_PIN is None: warn("`PKCS11_TOKEN_PIN' env variable is unset.") TOKEN_SO_PIN = os.environ.get('PKCS11_TOKEN_SO_PIN') if TOKEN_SO_PIN is None: TOKEN_SO_PIN = TOKEN_PIN warn("`PKCS11_TOKEN_SO_PIN' env variable is unset. Using value from `PKCS11_TOKEN_PIN'") OPENSSL = shutil.which('openssl', path=os.environ.get('OPENSSL_PATH')) if OPENSSL is None: warn("Path to OpenSSL not found. Please adjust `PATH' or define `OPENSSL_PATH'") class TestCase(unittest.TestCase): """Base test case, optionally creates a token and a session.""" with_token = True """Creates a token for this test case.""" with_session = True """Creates a session for this test case.""" @classmethod def setUpClass(cls): super().setUpClass() cls.lib = lib = pkcs11.lib(LIB) if cls.with_token or cls.with_session: cls.token = lib.get_token(token_label=TOKEN) def setUp(self): super().setUp() if self.with_session: self.session = self.token.open(user_pin=TOKEN_PIN) def tearDown(self): if self.with_session: self.session.close() super().tearDown() def requires(*mechanisms): """ Decorates a function or class as requiring mechanisms, else they are skipped. """ def check_requirements(self): """Determine what, if any, required mechanisms are unavailable.""" unavailable = set(mechanisms) - self.token.slot.get_mechanisms() if unavailable: raise unittest.SkipTest("Requires %s" % ', '.join(map(str, unavailable))) def inner(func): @wraps(func) def wrapper(self, *args, **kwargs): check_requirements(self) return func(self, *args, **kwargs) return wrapper return inner def xfail(condition): """Mark a test that's expected to fail for a given condition.""" def inner(func): if condition: return unittest.expectedFailure(func) else: return func return inner class Is: """ Test what device we're using. """ # trick: str.endswith() can accept tuples, # see https://stackoverflow.com/questions/18351951/check-if-string-ends-with-one-of-the-strings-from-a-list softhsm2 = LIB.lower().endswith(('libsofthsm2.so', 'libsofthsm2.dylib', 'softhsm2.dll', 'softhsm2-x64.dll')) nfast = LIB.lower().endswith(('libcknfast.so', 'cknfast.dll')) opencryptoki = LIB.endswith('libopencryptoki.so') travis = os.environ.get('TRAVIS') == 'true' class Avail: """ Test if a resource is available """ # openssl is searched across the exec path. Optionally, OPENSSL_PATH env variable can be defined # in case there is no direct path to it (i.e. PATH does not point to it) openssl = OPENSSL is not None class Only: """ Limit tests to given conditions """ softhsm2 = unittest.skipUnless(Is.softhsm2, "SoftHSMv2 only") openssl = unittest.skipUnless(Avail.openssl, "openssl not found in the path") class Not: """ Ignore tests for given devices """ softhsm2 = unittest.skipIf(Is.softhsm2, "Not supported by SoftHSMv2") nfast = unittest.skipIf(Is.nfast, "Not supported by nFast") opencryptoki = unittest.skipIf(Is.opencryptoki, "Not supported by OpenCryptoki") class FIXME: """ Tests is broken on this platform. """ softhsm2 = xfail(Is.softhsm2) nfast = xfail(Is.nfast) opencryptoki = xfail(Is.opencryptoki) travis = xfail(Is.travis) python-pkcs11-0.7.0/tests/test_iterators.py0000664000372000037200000000310513717606207021600 0ustar travistravis00000000000000""" Iterator tests """ import unittest import pkcs11 from . import TestCase, requires class IteratorTests(TestCase): @requires(pkcs11.Mechanism.AES_KEY_GEN, pkcs11.Mechanism.AES_CBC_PAD) def test_partial_decrypt(self): self.session.generate_key(pkcs11.KeyType.AES, 128, label='LOOK ME UP') key = self.session.get_key(label='LOOK ME UP') data = ( b'1234', b'1234', ) iv = self.session.generate_random(128) encrypted_data = list(key.encrypt(data, mechanism_param=iv)) iter1 = key.decrypt(encrypted_data, mechanism_param=iv) next(iter1) with self.assertRaises(pkcs11.OperationActive): iter2 = key.decrypt(encrypted_data, mechanism_param=iv) next(iter2) @requires(pkcs11.Mechanism.AES_KEY_GEN, pkcs11.Mechanism.AES_CBC_PAD) # Ideally deleting iterator #1 would terminate the operation, but it # currently does not. @unittest.expectedFailure def test_close_iterators(self): self.session.generate_key(pkcs11.KeyType.AES, 128, label='LOOK ME UP') key = self.session.get_key(label='LOOK ME UP') data = ( b'1234', b'1234', ) iv = self.session.generate_random(128) encrypted_data = list(key.encrypt(data, mechanism_param=iv)) iter1 = key.decrypt(encrypted_data, mechanism_param=iv) next(iter1) del iter1 iter2 = key.decrypt(encrypted_data, mechanism_param=iv) next(iter2)