def __menu_handler(args): if not Path(args.module).is_file(): print("(-module) path does not exist") exit() with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: serial_number = c.get_slot_info()[0].serialNumber print("") print("slot number: " + str(args.slot)) print("serial number: " + serial_number) # print header and print to console if not args.showAll: print("Handle".ljust(8) + "Label".ljust(30) + "Key Type".ljust(10) + "Class".ljust(15) + "Attributes".ljust(10)) print( "------- ----------------------------- --------- -------------- -------------" ) obj_list = c.get_objects(fast_load=True) else: obj_list = c.get_objects(fast_load=False) # loop the objects and print to console for o in obj_list: __print_object(o, args.showAll)
def __menu_handler(args): if not Path(args.module).is_file(): print("(-p11) path does not exist") exit() with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: c.destroy_object(handle=args.handle)
def __menu_handler(args): if not Path(args.module).is_file(): print("(-module) path does not exist") exit() print("starting test...") with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: unique_tag = bytes_to_hex(os.urandom(4)) key_handles = c.create_rsa_key_pair(public_key_label="RSA_PUB_TEST_KEY_{}".format(unique_tag), private_key_label="RSA_PVT_TEST_KEY_{}".format(unique_tag), mechanism=HsmMech[args.genMech], key_length=args.keySize, token=False, sign_verify=True, encrypt_decrypt=False, wrap_unwrap=False, public_private=False) pvt_h = key_handles[1] data = os.urandom(args.dataSize) # get start time t0 = time() try: for i in range(1, args.ops + 1): c.sign(handle=pvt_h, data=data, mechanism=HsmMech[args.signMech], pss_salt_length=args.pssSaltLength) except KeyboardInterrupt: print("interrupted") # get stop time t1 = time() print("end test") elapsed = t1 - t0 total_ops = args.ops print("\n-------------------------------------") print("RESULTS") print("-------------------------------------") print("test: rsasign-test") print("key_size: {}".format(args.keySize)) print("sign_mech: {}".format(args.signMech)) print("gen_mech: {}".format(args.genMech)) print("total_ops: {}".format(total_ops)) print("elapsed_time_ms: " + str(round(elapsed * 1000, 4))) print("ops/sec: " + str(round(total_ops / elapsed, 2))) print("-------------------------------------\n")
def __menu_handler(args): if not Path(args.module).is_file(): print("(-module) path does not exist") exit() with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: result = c.generate_random(size=args.size) if args.encoding == "hex": print(bytes_to_hex(result)) elif args.encoding == "base64": print(str(b64encode(result))[2:-1])
def __menu_handler(args): if not Path(args.module).is_file(): print("(-module) path does not exist") exit() with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: for mech in c.get_mechanism_info(args.slot): if args.showAll: print("----------------------------------------") print(mech.to_string()) else: print("{} ({})".format(mech.mechanismName, mech.mechanismValue))
def sign(self, handle, sigreq): logging.debug(f'Signing with HSM client:') logging.debug(f' Slot = {self.hsm_slot}') logging.debug(f' lib = {self.hsm_libfile}') logging.debug(f' handle = {handle}') with HsmClient(slot=self.hsm_slot, pin=self.hsm_pin, pkcs11_lib=self.hsm_libfile) as c: hashed_data = blake2b(hex_to_bytes(sigreq.get_payload()), digest_size=32).digest() logging.debug(f'Hashed data to sign: {hashed_data}') sig = c.sign(handle=handle, data=hashed_data, mechanism=HsmMech.ECDSA) logging.debug(f'Raw signature: {sig}') encoded_sig = Signer.b58encode_signature(sig) logging.debug(f'Base58-encoded signature: {encoded_sig}') return encoded_sig
def __menu_handler(args): if not Path(args.module).is_file(): print("(-p11) path does not exist") exit() with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: iv = c.generate_random(size=16) # CKM_AES_KEY_WRAP mech = 0x00002109 wrapped_key_bytes = c.wrap_key(key_handle=args.handle, wrap_key_handle=args.wrapHandle, wrap_key_iv=iv, wrap_key_mech=mech) print("iv: {}".format(bytes_to_hex(iv))) print("wrapped_key_bytes: {}".format(bytes_to_hex(wrapped_key_bytes)))
def __menu_handler(args): if not Path(args.module).is_file(): print("(-module) path does not exist") exit() print("starting test...") with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: # get start time t0 = time() try: for i in range(1, args.ops + 1): unique_tag = bytes_to_hex(os.urandom(4)) c.create_ecc_key_pair(public_key_label="EC_PUB_TEST_KEY_{}".format(unique_tag), private_key_label="EC_PVT_TEST_KEY_{}".format(unique_tag), ec_params=EcCurveOids[args.curveName], token=args.persist, sign_verify=True, encrypt_decrypt=False, wrap_unwrap=False, public_private=False) except KeyboardInterrupt: print("interrupted") # get stop time t1 = time() print("end test") elapsed = t1 - t0 total_ops = args.ops print("\n-------------------------------------") print("RESULTS") print("-------------------------------------") print("test: ecgen-test") print("curve: {}".format(args.curveName)) print("total_ops: {}".format(total_ops)) print("elapsed_time_ms: " + str(round(elapsed * 1000, 4))) print("ops/sec: " + str(round(total_ops / elapsed, 2))) print("-------------------------------------\n")
def sign(self, handle, test_mode=False): encoded_sig = '' data_to_sign = self.payload logging.info('About to sign {} with key handle {}'.format( data_to_sign, handle)) if self.valid_block_format(data_to_sign): logging.info('Block format is valid') if self.is_block() or self.is_endorsement(): logging.info('Preamble is valid') if self.is_within_level_threshold(): logging.info('Block level is valid') if test_mode: return self.TEST_SIGNATURE else: logging.info( 'About to sign with HSM client. Slot = {}, lib = {}, handle = {}' .format(self.hsm_slot, self.hsm_libfile, handle)) with HsmClient(slot=self.hsm_slot, pin=self.hsm_pin, pkcs11_lib=self.hsm_libfile) as c: hashed_data = blake2b(hex_to_bytes(data_to_sign), digest_size=32).digest() logging.info( 'Hashed data to sign: {}'.format(hashed_data)) sig = c.sign(handle=handle, data=hashed_data, mechanism=HsmMech.ECDSA) logging.info('Raw signature: {}'.format(sig)) encoded_sig = RemoteSigner.b58encode_signature(sig) logging.info('Base58-encoded signature: {}'.format( encoded_sig)) else: logging.error('Invalid level') raise Exception('Invalid level') else: logging.error('Invalid preamble') raise Exception('Invalid preamble') else: logging.error('Invalid payload') raise Exception('Invalid payload') return encoded_sig
def __menu_handler(args): if not Path(args.module).is_file(): print("(-p11) path does not exist") exit() # test to see if the user provided a pss salt length for a PSS algorithm if "PSS" in args.mech and args.pssSaltLength is None: print("-pss-length must be provided when a PSS mechanism is specified") return else: if args.pssSaltLength is None: args.pssSaltLength = 0 with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: sig = c.sign(handle=args.keyHandle, data=hex_to_bytes(args.data), mechanism=HsmMech[args.mech], pss_salt_length=args.pssSaltLength) print(bytes_to_hex(sig))
def __menu_handler(args): if not Path(args.module).is_file(): print("(-module) path does not exist") exit() with HsmClient(slot=args.slot, pin=args.pin, pkcs11_lib=args.module) as c: # create a new symmetric key on HSM hkey = c.create_secret_key(key_label=args.keyLabel, key_type=HsmSymKeyGen[args.keyType], key_size_in_bits=args.keySize, wrap=args.wrap, unwrap=args.unwrap, encrypt=args.encrypt, decrypt=args.decrypt, sign=args.sign, verify=args.verify, derive=args.derive, extractable=args.extractable, modifiable=args.modifiable, overwrite=args.overwrite, private=True, token=True) print("key with handle {} created on partition.".format(str(hkey)))
# # Copyright (c) 2016-present, Cisco Systems, Inc. All rights reserved. # # This source code is licensed under the GPL v2 license found in the # LICENSE.txt file in the root directory of this source tree. # import argparse from pyhsm.hsmclient import HsmClient parser = argparse.ArgumentParser("listslots", description="List HSM slots.") parser.add_argument("-p11", dest="module", required=True, help="Full path to HSM's PKCS#11 shared library.") args = parser.parse_args() # note: listing slot information does not require a login # example connects to the open source softHSM v2 with HsmClient(pkcs11_lib=args.module) as c: for s in c.get_slot_info(): print("----------------------------------------") print(s.to_string())
def sign(self, handle, test_mode=False): # This code acquires a mutex lock using https://github.com/chiradeep/dyndb-mutex # generate a unique name for this process/thread ddb_region = environ['REGION'] my_name = str(uuid.uuid4()).split("-")[0] if self.is_block(): sig_type = 'Baking' else: sig_type = 'Endorsement' m = DynamoDbMutex(sig_type, holder=my_name, timeoutms=60 * 1000, region_name=ddb_region) locked = m.lock() # attempt to acquire the lock if locked: encoded_sig = '' data_to_sign = self.payload logging.info('About to sign {} with key handle {}'.format( data_to_sign, handle)) if self.valid_block_format(data_to_sign): logging.info('Block format is valid') if self.is_block() or self.is_endorsement(): logging.info('Preamble is valid') if self.not_already_signed(): if test_mode: return self.TEST_SIGNATURE else: logging.info( 'About to sign with HSM client. Slot = {}, lib = {}, handle = {}' .format(self.hsm_slot, self.hsm_libfile, handle)) with HsmClient(slot=self.hsm_slot, pin=self.hsm_pin, pkcs11_lib=self.hsm_libfile) as c: hashed_data = blake2b( hex_to_bytes(data_to_sign), digest_size=32).digest() logging.info('Hashed data to sign: {}'.format( hashed_data)) sig = c.sign(handle=handle, data=hashed_data, mechanism=HsmMech.ECDSA) logging.info('Raw signature: {}'.format(sig)) encoded_sig = RemoteSigner.b58encode_signature( sig) logging.info( 'Base58-encoded signature: {}'.format( encoded_sig)) else: logging.error('Invalid level') m.release() # release the lock raise Exception('Invalid level') else: logging.error('Invalid preamble') m.release() # release the lock raise Exception('Invalid preamble') else: logging.error('Invalid payload') m.release() # release the lock raise Exception('Invalid payload') m.release() # release the lock return encoded_sig else: # lock could not be acquired logging.error('Could not acquire lock') raise Exception('Could not acquire lock')