Package: python-pkcs11
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 nCipherOpencryptoki TPMOpenSC/Smartcard-HSM/Nitrokey HSMSource:https://github.com/danni/python-pkcs11Documentation:http://python-pkcs11.readthedocs.io/en/latest/Getting StartedInstall from Pip:pip install python-pkcs11Or build from source:python setup.py buildAssuming your PKCS#11 library is set asPKCS11_MODULEand contains a
token namedDEMO:AESimport 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)3DESimport 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)RSAimport 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)DSAimport 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)ECDSAimport 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-Hellmanimport 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-Hellmanimport 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 <named curve>
    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 CompatibilityFunctionalitySoftHSMv2Thales nCipherOpencryptokiOpenSC (Nitrokey)Get Slots/TokensWorksWorksWorksWorksGet MechanismsWorksWorksWorksWorksInitialize tokenNot implementedSlot eventsNot implementedAlternative authentication
pathNot implementedAlways authenticatekeysNot implementedCreate/CopyKeysWorksWorksErrorsCreateCertificatesCaveats[1]Caveats[1]Caveats[1]?Domain ParamsCaveats[1]Caveats[1]?N/ADestroy ObjectWorksN/AWorksWorksGenerate RandomWorksWorksWorksWorksSeed RandomWorksN/AN/AN/ADigest (Data & Keys)WorksCaveats[2]WorksWorksAESGenerate keyWorksWorksWorksN/AEncrypt/DecryptWorksWorksWorksWrap/Unwrap?[3]WorksErrorsSign/VerifyWorksWorks[4]N/ADES2/
DES3Generate keyWorksWorksWorksN/AEncrypt/DecryptWorksWorksWorksWrap/Unwrap???Sign/Verify???RSAGenerate key pairWorksWorksWorksWorks[4][8]Encrypt/DecryptWorksWorksWorksDecrypt only[9]Wrap/UnwrapWorksWorksWorksN/ASign/VerifyWorksWorksWorksWorksDSAGenerate parametersWorksErrorN/AN/AGenerate key pairWorksCaveats[5]Sign/VerifyWorksWorks[4]DHGenerate parametersWorksN/AN/AN/AGenerate key pairWorksCaveats[6]Derive KeyWorksCaveats[7]ECGenerate key pairCaveats[6]?[3]N/AWorksSign/Verify (ECDSA)Works[4]?[3]Sign only[9]Derive key (ECDH)Works?[3]?Proprietary extensionsN/ANot implementedN/AN/A[1](1,2,3,4,5)Device supports limited set of attributes.[2]Digesting keys is not supported.[3](1,2,3,4)Untested: requires support in device.[4](1,2,3,4)Default mechanism not supported, must specify a mechanism.[5]From existing domain parameters.[6](1,2)Local domain parameters only.[7]Generates security warnings about the derived key.[8]storeparameter is ignored, all keys are stored.[9](1,2)Encryption/verify not supported, extract the public keyPython version:3.4 (withaenum)3.5 (withaenum)3.6PKCS#11 versions:2.112.202.40Feel 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 #11The 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.htmlYou 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.LicenseMIT LicenseCopyright (c) 2017 Danielle MadeleyPermission 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.