def open_pkcs11_session(lib_location, slot_no=None, token_label=None, user_pin=None) -> Session: """ Open a PKCS#11 session :param lib_location: Path to the PKCS#11 module. :param slot_no: Slot number to use. If not specified, the first slot containing a token labelled ``token_label`` will be used. :param token_label: Label of the token to use. If ``None``, there is no constraint. :param user_pin: User PIN to use. .. note:: Some PKCS#11 implementations do not require PIN when the token is opened, but will prompt for it out-of-band when signing. :return: An open PKCS#11 session object. """ lib = pkcs11_lib(lib_location) slots = lib.get_slots() token = None if slot_no is None: for slot in slots: try: token = slot.get_token() if token_label is None or token.label == token_label: break except PKCS11Error: continue if token is None: raise PKCS11Error( f'No token with label {token_label} found' if token_label is not None else 'No token found' ) else: token = slots[slot_no].get_token() if token_label is not None and token.label != token_label: raise PKCS11Error('Token in slot %d is not BELPIC.' % slot_no) kwargs = {} if user_pin is not None: kwargs['user_pin'] = user_pin return token.open(**kwargs)
def open_beid_session(lib_location, slot_no=None) -> Session: """ Open a PKCS#11 session :param lib_location: Path to the shared library file containing the eID PKCS#11 module. Usually, the file is named ``libbeidpkcs11.so``, ``libbeidpkcs11.dylib`` or ``beidpkcs11.dll``, depending on your operating system. :param slot_no: Slot number to use. If not specified, the first slot containing a token labelled ``BELPIC`` will be used. :return: An open PKCS#11 session object. """ lib = pkcs11_lib(lib_location) slots = lib.get_slots() token = None if slot_no is None: for slot in slots: try: token = slot.get_token() if token.label == 'BELPIC': break except PKCS11Error: continue if token is None: raise PKCS11Error('No BELPIC token found') else: token = slots[slot_no].get_token() if token.label != 'BELPIC': raise PKCS11Error('Token in slot %d is not BELPIC.' % slot_no) # the middleware will prompt for the user's PIN when we attempt # to sign later, so there's no need to specify it here return token.open()