Beispiel #1
0
    def test_destroymultipleobjects(self):
        """
        Test deletion of multiple keys
        Tested by RSA key pair
        """

        key_type, pub_key_temp, priv_key_temp = pair_params(
            CKM_RSA_PKCS_KEY_PAIR_GEN)
        session_pub_template = get_session_template(pub_key_temp)
        session_priv_template = get_session_template(priv_key_temp)
        ret, pub_key, prv_key = c_generate_key_pair(self.h_session, key_type,
                                                    session_pub_template,
                                                    session_priv_template)

        try:

            ret = ca_destroy_multiple_objects_ex(self.h_session,
                                                 [pub_key, prv_key])
            self.verify_ret(ret, CKR_OK)
            for templ in (session_pub_template, session_priv_template):
                objs = c_find_objects_ex(self.h_session, templ, 1)
                assert len(objs) == 0

        except Exception:
            for key in (pub_key, prv_key):
                c_destroy_object(self.h_session, key)
def list_kek_labels(password):
    '''
        List labels of upto 100 keys
        password - string CryptoUser role password
    '''

    # HSM slot id for HA
    slot_id = 5
    labels = []
    try:
        auth_session = None
        _initialize()
        auth_session = c_open_session_ex(slot_id)
        login_ex(auth_session, slot_id, password, CKU_CRYPTO_USER)

        key_handles = c_find_objects_ex(auth_session, {CKA_KEY_TYPE: CKK_AES},
                                        100)
        for handle in key_handles:
            label = c_get_attribute_value_ex(
                auth_session, handle,
                Attributes({CKA_LABEL: b'01234567890123456789012345'}))
            labels.append(label[3].decode("utf-8"))
    except LunaCallException:
        print("Exception running key mgmt operation")
        print(traceback.format_exc())
        raise Exception('Exception running key mgmt operation')
    finally:
        if auth_session:
            c_logout_ex(auth_session)
            c_close_session_ex(auth_session)
        c_finalize_ex()

    return labels
def encrypt(password, kek_label, plaintext_path):
    '''
        Encrypt plain text to cipher text
        password - string CryptoUser role password
        kek_label - string label of decryption key in HSM
        plaintext_path - path of base64 encoded data to be encrypted
    '''
    plaintext = open(plaintext_path, 'rb').read()
    encrypted = None
    i = 0
    while i < 2:
        try:
            auth_session = None
            _initialize()
            auth_session = c_open_session_ex(i)
            login_ex(auth_session, i, password, CKU_CRYPTO_USER)

            kek_handle = None
            kek_handle = c_find_objects_ex(auth_session, {
                CKA_KEY_TYPE: CKK_AES,
                CKA_LABEL: kek_label
            }, 1)
            if kek_handle:
                params = {"iv": list(range(16)), "AAD": [], "ulTagBits": 128}
                mechanism = Mechanism(mech_type=CKM_AES_GCM, params=params)
                encrypted = c_encrypt_ex(auth_session, kek_handle[0],
                                         plaintext, mechanism)
                encrypted = array.array('B', list(
                    range(16))).tostring() + encrypted
                break
            else:
                i += 1
        except LunaCallException:
            print("Exception running key mgmt operation on slot " + str(i))
            print(traceback.format_exc())
            i += 1
        finally:
            if auth_session:
                c_logout_ex(auth_session)
                c_close_session_ex(auth_session)
            c_finalize_ex()

    if encrypted:
        ciphertext = base64.b64encode(encrypted)
        return ciphertext
    else:
        raise Exception("Failed to encrypt DEK")
Beispiel #4
0
def partition_clearer(auth_session):
    """
    Autoused fixture to make sure the active session is cleared from all created objects.

    :param auth_session:
    :return:
    """
    yield
    try:
        # Use a blank template so we can grab everything.
        template = Attributes({}).get_c_struct()
        objects = c_find_objects_ex(auth_session, template, 1000)
        for handle in objects:
            ret = c_destroy_object(auth_session, handle)
            if ret != CKR_OK:
                LOG.info("Failed to destroy object w/ handle %s", handle)
    except LunaException:
        LOG.exception("Failed to destroy all objects created on this session")
def decrypt(password, kek_label, path_to_plain_text):
    '''
        Decrypt cipher text to plain text
        password - string CryptoUser role password
        kek_label - string label of decryption key in HSM
        path_to_plain_text - path of base64 encoded data to be decrypted
    '''
    ciphertext = open(path_to_plain_text, 'rb').read()
    decrypted = None
    i = 0
    while i < 2:
        try:
            cipher = base64.b64decode(ciphertext)
            auth_session = None
            _initialize()
            auth_session = c_open_session_ex(i)
            login_ex(auth_session, i, password, CKU_CRYPTO_USER)

            kek_handle = None
            kek_handle = c_find_objects_ex(auth_session,
                                           {CKA_KEY_TYPE: CKK_AES, CKA_LABEL: kek_label},
                                           1)
            if kek_handle:
                params = {"iv": cipher[:16], "AAD": [], "ulTagBits": 128}
                mechanism = Mechanism(mech_type=CKM_AES_GCM, params=params)
                decrypted = c_decrypt_ex(auth_session, kek_handle[0], cipher[16:], mechanism)
                break
            else:
                i += 1
        except LunaCallException:
            i += 1
        except Exception:
            raise("Failed to decrypt DEK")
        finally:
            if auth_session:
                c_logout_ex(auth_session)
                c_close_session_ex(auth_session)
            c_finalize_ex()

    if decrypted:
        return decrypted
    else:
        raise Exception("Failed to decrypt DEK")
from pycryptoki.session_management import *
from pycryptoki.defines import *  # imports CKA_*s
from pycryptoki.object_attr_lookup import c_find_objects_ex
from pycryptoki.key_generator import c_destroy_object_ex

c_initialize_ex()
auth_session = c_open_session_ex(3)  # HSM slot # in this example is 3
login_ex(
    auth_session, 3, "crypto-officer-pin"
)  # 3 is still the slot number, ´crypto-officer-pin´ should be replaced by your Crypto Officer password (None if PED or no challenge)

# The label/search string to find private key:
search_template = {CKA_LABEL: b"1BTC Private"}

# Delete all keys found with the search:
keys = c_find_objects_ex(auth_session, search_template, 1)
print(keys)
key = keys.pop(0)
c_destroy_object_ex(auth_session, key)

# Deleting the public key
search_template = {CKA_LABEL: b"1BTC Public"}
keys = c_find_objects_ex(auth_session, search_template, 1)
print(keys)
key = keys.pop(0)
c_destroy_object_ex(auth_session, key)

print('Key(s) deleted')

c_logout_ex(auth_session)
c_close_session_ex(auth_session)