Exemplo n.º 1
0
    def _query_handle(self, handle, klass, object_info_type):
        """Gets the object handle info.

        Parameters
        ----------


        handle: HANDLE
            handle object
        klass: int
            the class of information to query
        object_info_type: Structure
            structure type which holds the handle info
        """
        buff = malloc(self._object_buff_size)
        rlen = ULONG()
        status = nt_query_object(handle, klass, buff, self._object_buff_size,
                                 byref(rlen))
        if status >= 0:
            info = cast(buff, POINTER(object_info_type))
            self._buffers.append(buff)
            return info
        else:
            # reallocate the buffer size
            # and try again
            buff = realloc(buff, rlen.value)
            status = nt_query_object(handle, klass, buff,
                                     self._object_buff_size, None)
            if status >= 0:
                info = cast(buff, POINTER(object_info_type))
                self._buffers.append(buff)
                return info
            else:
                free(buff)
                return None
Exemplo n.º 2
0
 def __init__(self, expr: Union[POINTER(Texpr1), PyLinexpr1]):
     if isinstance(expr, PyLinexpr1):
         self.texpr1: POINTER(Texpr1) = libapron.ap_texpr1_from_linexpr1(
             expr)
     else:
         assert isinstance(expr, POINTER(Texpr1))
         self.texpr1: POINTER(Texpr1) = expr
Exemplo n.º 3
0
class PEB(Structure):
    _fields_ = [('reserved1', BYTE * 2), ('being_debugged', BYTE),
                ('reserved2', BYTE * 21), ('ldr', POINTER(PEB_LDR_DATA)),
                ('process_parameters', POINTER(RTL_USER_PROCESS_PARAMETERS)),
                ('reserved3', BYTE * 520),
                ('post_process_init_routine', PVOID),
                ('reserved4', BYTE * 136), ('session_id', ULONG)]
Exemplo n.º 4
0
def IIterator(T):
    cls = pinterface_type('IIterator', '6a79e863-4300-459a-9966-cbb660963ee1', (T,), (IInspectable, IIterator_helpers))
    define_winrt_com_method(cls, 'get_Current', propget=T, vtbl=6)
    define_winrt_com_method(cls, 'get_HasCurrent', propget=c_bool, vtbl=7)
    define_winrt_com_method(cls, 'MoveNext', retval=c_bool, vtbl=8)
    define_winrt_com_method(cls, 'GetMany', c_uint, POINTER(T), POINTER(c_uint), retval=c_uint32, vtbl=9)
    return cls
Exemplo n.º 5
0
def IVectorView(T):
    cls = pinterface_type('IVectorView', 'bbe1fa4c-b0e3-4583-baef-1f1b2e483e56', (T,), (IIterable(T), IVectorView_helpers))
    define_winrt_com_method(cls, 'GetAt', c_uint, retval=T, vtbl=6)
    define_winrt_com_method(cls, 'get_Size', propget=c_uint32, vtbl=7)
    define_winrt_com_method(cls, 'IndexOf', T, POINTER(c_uint32), retval=c_bool, vtbl=8)
    define_winrt_com_method(cls, 'GetMany', c_uint, c_uint, POINTER(IInspectable), POINTER(c_uint), vtbl=9)
    return cls
Exemplo n.º 6
0
def ca_set_authorization_data(h_session, h_object, old_auth_data,
                              new_auth_data):
    """
    User changes authorization data on key object (private, secret)

    :param h_session: session handle
    :param object: key handle to update
    :param old_auth_data: byte list, e.g. [11, 12, 13, ..]
    :param new_auth_data: byte list, e.g. [11, 12, 13, ..]
    :return: Ret code
    """
    old_auth_data_ptr, old_auth_data_length = to_byte_array(old_auth_data)
    old_auth_data_ptr = cast(old_auth_data_ptr, POINTER(CK_UTF8CHAR))

    new_auth_data_ptr, new_auth_data_length = to_byte_array(new_auth_data)
    new_auth_data_ptr = cast(new_auth_data_ptr, POINTER(CK_UTF8CHAR))

    h_object = CK_OBJECT_HANDLE(h_object)
    h_session = CK_SESSION_HANDLE(h_session)

    return CA_SetAuthorizationData(
        h_session,
        h_object,
        old_auth_data_ptr,
        old_auth_data_length,
        new_auth_data_ptr,
        new_auth_data_length,
    )
Exemplo n.º 7
0
def _reset_cache():
    _pointer_type_cache.clear()
    _c_functype_cache.clear()
    if _os.name in ("nt", "ce"):
        _win_functype_cache.clear()
    POINTER(c_wchar).from_param = c_wchar_p.from_param
    POINTER(c_char).from_param = c_char_p.from_param
    _pointer_type_cache[None] = c_void_p
    CFUNCTYPE(c_int)(lambda: None)
Exemplo n.º 8
0
    class P(Union):
        """
        union {
          ap_coeff_t* coeff;     /* array of coefficients */
          ap_linterm_t* linterm; /* array of linear terms */
        } p;
        """

        _fields_ = [('coeff', POINTER(Coeff)), ('linterm', POINTER(LinTerm))]
Exemplo n.º 9
0
class OVERLAPPED(Structure):
    _fields_ = [
        ("Internal", POINTER(ULONG)),
        ("InternalHigh", POINTER(ULONG)),
        ("u", _U),
        ("hEvent", HANDLE),
    ]

    _anonymous_ = ("u", )
Exemplo n.º 10
0
class Texpr1(Structure):
    """
    typedef struct ap_texpr1_t {
      ap_texpr0_t* texpr0;
      ap_environment_t* env;
    } ap_texpr1_t;
    """

    _fields_ = [('texpr0', POINTER(Texpr0)), ('env', POINTER(Environment))]

    def __repr__(self):
        def precendence(texpr0):
            op_precedence = {
                TexprOp.AP_TEXPR_ADD: 1,
                TexprOp.AP_TEXPR_SUB: 1,
                TexprOp.AP_TEXPR_MUL: 2,
                TexprOp.AP_TEXPR_DIV: 2,
                TexprOp.AP_TEXPR_MOD: 2,
                TexprOp.AP_TEXPR_POW: 3,
                TexprOp.AP_TEXPR_NEG: 4,
                TexprOp.AP_TEXPR_CAST: 5,
                TexprOp.AP_TEXPR_SQRT: 5
            }
            if texpr0.discr == TexprDiscr.AP_TEXPR_CST or texpr0.discr == TexprDiscr.AP_TEXPR_DIM:
                return op_precedence[TexprOp.AP_TEXPR_NEG]
            return op_precedence[texpr0.val.node.contents.op]

        def do(texpr0, env):
            if texpr0.discr == TexprDiscr.AP_TEXPR_CST:
                return '{}'.format(texpr0.val.cst)
            elif texpr0.discr == TexprDiscr.AP_TEXPR_DIM:
                return '{}'.format(
                    env.var_of_dim[texpr0.val.dim.value].decode('utf-8'))
            else:  # texpr0.discr == TexprDiscr.AP_TEXPR_NODE
                prec = precendence(texpr0)
                prec_a = precendence(texpr0.val.node.contents.exprA.contents)
                if prec_a < prec:
                    expr_a = '({})'.format(
                        do(texpr0.val.node.contents.exprA.contents, env))
                else:
                    expr_a = do(texpr0.val.node.contents.exprA.contents, env)
                op = texpr0.val.node.contents.op
                if texpr0.val.node.contents.exprB:  # binary operation
                    prec_b = precendence(
                        texpr0.val.node.contents.exprB.contents)
                    if prec_b <= prec:
                        expr_b = '({})'.format(
                            do(texpr0.val.node.contents.exprB.contents, env))
                    else:
                        expr_b = do(texpr0.val.node.contents.exprB.contents,
                                    env)
                    return '{} {} {}'.format(expr_a, repr(TexprOp(op)), expr_b)
                else:
                    return '{} {}'.format(repr(TexprOp(op)), expr_a)

        return do(self.texpr0.contents, self.env.contents).replace('+ -', '- ')
Exemplo n.º 11
0
def _reset_cache():
    _pointer_type_cache.clear()
    _c_functype_cache.clear()
    if _os.name == "nt":
        _win_functype_cache.clear()
    # _SimpleCData.c_wchar_p_from_param
    POINTER(c_wchar).from_param = c_wchar_p.from_param
    # _SimpleCData.c_char_p_from_param
    POINTER(c_char).from_param = c_char_p.from_param
    _pointer_type_cache[None] = c_void_p
Exemplo n.º 12
0
    class Val(Union):
        """
        union {
          ap_scalar_t* scalar;       /* cst (normal linear expression) */
          ap_interval_t* interval;   /* interval (quasi-linear expression) */
        } val;
        """

        _fields_ = [('scalar', POINTER(Scalar)),
                    ('interval', POINTER(Interval))]
Exemplo n.º 13
0
class Lincons0(Structure):
    """
    typedef struct ap_lincons0_t {
      ap_linexpr0_t* linexpr0;  /* expression */
      ap_constyp_t constyp;     /* type of constraint */
      ap_scalar_t* scalar;      /* maybe NULL. For EQMOD constraint, indicates the modulo */
    } ap_lincons0_t;
    """

    _fields_ = [('linexpr0', POINTER(Linexpr0)), ('constyp', c_uint),
                ('scalar', POINTER(Scalar))]
Exemplo n.º 14
0
class tRecognitionEngineSettings(Structure):
    _fields_ = [('miliseconds', c_long), ('bApplyCorrection', c_long),
                ('fDistance', c_float), ('fVerticalCoeff', c_float),
                ('fHorizontalCoeff', c_float), ('fAngle', c_float),
                ('fRadialCoeff', c_float), ('fVerticalScrew', c_float),
                ('fHorizontalScrew', c_float), ('lNumSteps', c_long),
                ('vlSteps', c_long * MAX_STEPS), ('lLeft', c_long),
                ('lTop', c_long), ('lWidth', c_long), ('lHeight', c_long),
                ('fScale', c_float), ('lUserParam1', POINTER(c_void_p)),
                ('lUserParam2', POINTER(c_void_p)),
                ('lUserParam3', POINTER(c_void_p)), ('SlantDetection', c_long),
                ('KillerShadow', c_long), ('CharacterRectangle', c_bool)]
Exemplo n.º 15
0
class Abstract1(Structure):
    """
    typedef struct ap_abstract1_t {
      ap_abstract0_t* abstract0;
      ap_environment_t* env;
    } ap_abstract1_t;
    """

    _fields_ = [
        ('abstract0', POINTER(Abstract0)),
        ('env', POINTER(Environment))
    ]
Exemplo n.º 16
0
class Interval(Structure):
    """
    typedef struct ap_interval_t {
      ap_scalar_t* inf;
      ap_scalar_t* sup;
    } ap_interval_t;
    """

    _fields_ = [('inf', POINTER(Scalar)), ('sup', POINTER(Scalar))]

    def __repr__(self):
        return '[{},{}]'.format(self.inf.contents, self.sup.contents)
Exemplo n.º 17
0
def c_verify(h_session, h_key, data_to_verify, signature, mechanism):
    """Verifies data with the given signature, key and mechanism.

    .. note:: If data is a list or tuple of strings, multi-part operations will be used.

    :param int h_session: Session handle
    :param data_to_verify: The data to sign, either a string or a list of strings. If this is a list
                         a multipart operation will be used.

                         ex:

                         - "This is a proper argument of some data to use in the function"
                         - ["This is another format of data this", "function will accept.",
                           "It will operate on these strings in parts"]
    :param bytes signature: Signature with which to verify the data.
    :param int h_key: The verifying key
    :param mechanism: See the :py:func:`~pypkcs11.mechanism.parse_mechanism` function
        for possible values.
    :return: retcode of verify operation
    """

    mech = parse_mechanism(mechanism)

    # Initialize the verify operation
    ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key))
    if ret != CKR_OK:
        return ret

    # if a list is passed out do a verify operation on each string in the list,
    # otherwise just do one verify operation
    is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(
        data_to_verify, tuple)

    if is_multi_part_operation:
        ret = do_multipart_verify(h_session, data_to_verify, signature)
    else:
        # Prepare the data to verify
        c_data_to_verify, plain_data_len = to_byte_array(
            from_bytestring(data_to_verify))
        c_data_to_verify = cast(c_data_to_verify, POINTER(c_ubyte))

        c_signature, c_sig_length = to_byte_array(from_bytestring(signature))
        c_signature = cast(c_signature, POINTER(c_ubyte))

        # Actually verify the data
        ret = C_Verify(h_session, c_data_to_verify, plain_data_len,
                       c_signature, c_sig_length)

    return ret
Exemplo n.º 18
0
def c_verify(h_session, h_key, data_to_verify, signature, mechanism):
    """
    Return the result code of C_Verify which indicates whether or not the signature is
    valid.

    :param h_session: The current session
    :param h_key: The key handle to verify the signature against
    :param data_to_verify: The data to verify, either a string or a list of strings. If this is a
                           list, a multipart operation will be used (using C_...Update and
                           C_...Final)

                           ex:

                           - "This is a proper argument of some data to use in the function"
                           - ["This is another format of data this", "function will accept.",
                             "It will operate on these strings in parts"]

    :param signature: The signature of the data
    :param mechanism: Will create a mechanism with the :py:func:`mechanism.parse_mechanism` function
    :return: The result code
    """

    mech = parse_mechanism(mechanism)

    # Initialize the verify operation
    ret = C_VerifyInit(h_session, mech, CK_ULONG(h_key))
    if ret != CKR_OK:
        return ret

    # if a list is passed out do a verify operation on each string in the list,
    # otherwise just do one verify operation
    is_multi_part_operation = isinstance(data_to_verify, list) or isinstance(
        data_to_verify, tuple)

    if is_multi_part_operation:
        ret = do_multipart_verify(h_session, data_to_verify, signature)
    else:
        # Prepare the data to verify
        c_data_to_verify, plain_date_len = to_char_array(data_to_verify)
        c_data_to_verify = cast(c_data_to_verify, POINTER(c_ubyte))

        c_signature, c_sig_length = to_char_array(signature)
        c_signature = cast(c_signature, POINTER(c_ubyte))

        # Actually verify the data
        ret = C_Verify(h_session, c_data_to_verify, plain_date_len,
                       c_signature, c_sig_length)

    return ret
Exemplo n.º 19
0
def _reset_cache():
    _pointer_type_cache.clear()
    _c_functype_cache.clear()
    if _os.name in ("nt", "ce"):
        _win_functype_cache.clear()
    # _SimpleCData.c_wchar_p_from_param
    POINTER(c_wchar).from_param = c_wchar_p.from_param
    # _SimpleCData.c_char_p_from_param
    POINTER(c_char).from_param = c_char_p.from_param
    _pointer_type_cache[None] = c_void_p
    # XXX for whatever reasons, creating the first instance of a callback
    # function is needed for the unittests on Win64 to succeed.  This MAY
    # be a compiler bug, since the problem occurs only when _ctypes is
    # compiled with the MS SDK compiler.  Or an uninitialized variable?
    CFUNCTYPE(c_int)(lambda: None)
Exemplo n.º 20
0
def c_multiplication(a, b):
    class Collection(Structure):
        _fields_ = [("size", c_int),
                    ("data", (c_float * a.shape[1]) * a.shape[0])]

    libmatmult = ctypes.CDLL("./multiply.so")

    libmatmult.multiply.argtypes = [POINTER(Collection)]
    libmatmult.multiply.restype = None

    t_a = Collection()
    t_b = Collection()
    t_c = Collection()

    for i in range(a.shape[0]):
        for j in range(a.shape[1]):
            t_a.data[i][j] = a[i][j]
            t_c.data[i][j] = a[i][j]

    for i in range(b.shape[0]):
        for j in range(b.shape[1]):
            t_b.data[i][j] = b[i][j]

    start = time.time()
    libmatmult.multiply(byref(t_a), byref(t_b), byref(t_c), a.shape[0],
                        a.shape[1])
    end = time.time()
    print(end - start)

    c_result = np.ones(a.shape)
    for i in range(a.shape[0]):
        for j in range(a.shape[1]):
            c_result = (t_c.data[i][j])
    return c_result
Exemplo n.º 21
0
    def preview(self):
        try:
            self.lock.acquire()
            self.enable_liveview()

            logging.debug('** camera preview')
            retval = gp.gp_camera_capture_preview(self.camera,
                                                  self.preview_file,
                                                  self.context)
            if retval != GP_OK:
                # logging.error('preview capture error %s', retval)
                return None

            data = ctypes.c_void_p()
            length = ctypes.c_ulong()
            retval = gp.gp_file_get_data_and_size(self.preview_file,
                                                  ctypes.byref(data),
                                                  ctypes.byref(length))
            if retval != GP_OK or data.value is None:
                logging.error('preview fetch error %s', retval)
                return None

            logging.debug('preview: frame at addr %d, length %d', data.value,
                          length.value)

            try:
                # see effbot.org/imagingbook/introduction.html#more-on-reading-images
                res = ctypes.cast(data, POINTER(ctypes.c_ubyte *
                                                length.value)).contents
                file_jpgdata = None

                if self.focuspeak_enabled is False:
                    file_jpgdata = StringIO(res)
                else:
                    img_buffer = np.asarray(bytearray(res), dtype=np.uint8)
                    im = cv2.imdecode(img_buffer, cv2.CV_LOAD_IMAGE_COLOR)
                    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
                    blur = cv2.GaussianBlur(gray, (5, 5), 0)
                    canny = cv2.Canny(blur, 0, 150)

                    colorIm = np.zeros(im.shape, im.dtype)
                    colorIm[:, :] = (255, 0, 255)

                    colorMask = cv2.bitwise_and(colorIm, colorIm, mask=canny)
                    cv2.addWeighted(colorMask, 1, im, 1, 0, im)
                    retval, im2 = cv2.imencode('.jpg', im)
                    file_jpgdata = StringIO(im2.tostring())

                #im = Image.open(file_jpgdata)
                #im.show()

                data = file_jpgdata
            except Exception as ex:
                print(ex)
                logging.error('failed')

            #lock.release()
            return data, length.value
        finally:
            self.lock.release()
Exemplo n.º 22
0
 class PROCESSENTRY32(Structure):
     _fields_ = [('dwSize', DWORD), ('cntUsage', DWORD),
                 ('th32ProcessID', DWORD),
                 ('th32DefaultHeapID', POINTER(ULONG)),
                 ('th32ModuleID', DWORD), ('cntThreads', DWORD),
                 ('th32ParentProcessID', DWORD), ('pcPriClassBase', LONG),
                 ('dwFlags', DWORD), ('szExeFile', c_char * MAX_PATH)]
Exemplo n.º 23
0
    def array(self):
        """
        Allows for dynamic returning of data.

        If size is None, return None.
        If size is not None and internal array is None, return a pointer to a
        allocated memory of size self.ctype * self.size
        If size is not None, and internal array is not None, returna pointer to the
        allocated memory of the internal array.

        .. warning:: This will ONLY work properly if ``array`` is read before ``size``!
            You can assign to temporary values to work around this if the PKCS call requires the
            size first::

                array, len = autoarray.array, autoarray.size

            This is because after ``size`` is read, ``array`` is initialized to a C array of the
            given value.


        :return: pointer to the internal array.
        :rtype: POINTER
        """
        if self._size is None:
            # Return None, because this is the first time we've used this array.
            # We need to set the size first w/ a call.
            return None
        if self._array is None:
            # If we get to this point, we have a specified size, a ctype,
            # And our array is still none, but we're trying to access it.
            # Therefore, we go ahead & allocate the memory
            LOG.debug("Allocating %s buffer of size: %s", self.ctype, self._size.value)
            self._array = (self.ctype * self._size.value)()
        return cast(self._array, POINTER(self.ctype))
Exemplo n.º 24
0
def do_multipart_operation(h_session, c_update_function, c_finalize_function,
                           input_data_list):
    """Some code which will do a multipart encrypt or decrypt since they are the same
    with just different functions called

    :param h_session: Session handle.
    :param c_update_function: C_<NAME>Update function to call to update each operation.
    :param c_finalize_function: Function to call at end of multipart operation.
    :param input_data_list: List of data to call update function on.
    """
    max_data_chunk_size = 0xfff0
    plain_data_len = len(b"".join(input_data_list))

    remaining_length = plain_data_len
    python_data = []
    i = 0
    while remaining_length > 0:
        current_chunk = input_data_list[i]

        # Prepare arguments for decrypt update operation
        current_chunk_len = min(len(current_chunk), remaining_length)

        if current_chunk_len > max_data_chunk_size:
            raise ValueError("chunk_sizes variable too large,"
                             " the maximum size of a chunk is %s" %
                             max_data_chunk_size)

        out_data = create_string_buffer(b'', max_data_chunk_size)
        out_data_len = CK_ULONG(max_data_chunk_size)
        data_chunk, data_chunk_len = to_char_array(current_chunk)
        data_chunk = cast(data_chunk, POINTER(c_ubyte))

        ret = c_update_function(h_session, data_chunk, data_chunk_len,
                                cast(out_data, CK_BYTE_PTR),
                                byref(out_data_len))
        if ret != CKR_OK:
            LOG.debug(
                "Failed C_Update operation on chunk %.20s (%s/%s) - ret %s",
                current_chunk, i, len(input_data_list),
                ret_vals_dictionary[ret])
            return ret, None

        remaining_length -= current_chunk_len

        # Get the output
        python_data.append(string_at(out_data, out_data_len.value))
        i += 1

    # Finalizing multipart decrypt operation
    fin_out_data_len = CK_ULONG(max_data_chunk_size)
    fin_out_data = create_string_buffer(b"", fin_out_data_len.value)
    output = cast(fin_out_data, CK_BYTE_PTR)
    ret = c_finalize_function(h_session, output, byref(fin_out_data_len))
    if ret != CKR_OK:
        return ret, None

    if fin_out_data_len.value > 0:
        python_data.append(string_at(fin_out_data, fin_out_data_len.value))

    return ret, b"".join(python_data)
Exemplo n.º 25
0
 def __init__(self, manager: PyManager,
              abstract1_or_environment: Union[Abstract1, PyEnvironment],
              bottom: bool = False, array: Union[PyLincons1Array, PyTcons1Array] = None,
              variables: List[PyVar] = None, intervals: List[PyInterval] = None):
     self.manager = manager
     if isinstance(abstract1_or_environment, Abstract1):
         self.abstract1 = abstract1_or_environment
     elif bottom:
         assert isinstance(abstract1_or_environment, PyEnvironment)
         self.abstract1 = libapron.ap_abstract1_bottom(self.manager, abstract1_or_environment)
     elif array and isinstance(array, PyLincons1Array):
         assert isinstance(abstract1_or_environment, PyEnvironment)
         man = self.manager
         a1 = libapron.ap_abstract1_of_lincons_array(man, abstract1_or_environment, array)
         self.abstract1 = a1
     elif array and isinstance(array, PyTcons1Array):
         assert isinstance(abstract1_or_environment, PyEnvironment)
         man = self.manager
         a1 = libapron.ap_abstract1_of_tcons_array(man, abstract1_or_environment, array)
         self.abstract1 = a1
     elif variables and intervals:
         assert isinstance(abstract1_or_environment, PyEnvironment)
         size = len(variables)
         v_typ: Type = c_char_p * size
         v_arr = v_typ(*(x._as_parameter_ for x in variables))
         i_typ: Type = POINTER(Interval) * size
         i_arr = i_typ(*(x._as_parameter_ for x in intervals))
         man = self.manager
         a1 = libapron.ap_abstract1_of_box(man, abstract1_or_environment, v_arr, i_arr, size)
         self.abstract1 = a1
     else:
         assert isinstance(abstract1_or_environment, PyEnvironment)
         self.abstract1 = libapron.ap_abstract1_top(self.manager, abstract1_or_environment)
Exemplo n.º 26
0
class tResults(Structure):
    _fields_ = [
        ('lRes', c_long), ('lNumberOfPlates', c_long),
        ('strResult', c_char * MAX_PLATES * MAX_CHARACTERS),
        ('vlNumbersOfCharacters', c_long * MAX_PLATES),
        ('vlGlobalConfidence', c_float * MAX_PLATES),
        ('vfAverageCharacterHeight', c_float * MAX_PLATES),
        ('vfCharacterConfidence', c_float * MAX_PLATES * MAX_CHARACTERS),
        ('vlLeft', c_long * MAX_PLATES), ('vlTop', c_long * MAX_PLATES),
        ('vlRight', c_long * MAX_PLATES), ('vlBottom', c_long * MAX_PLATES),
        ('lProcessingTime', c_long), ('vlFormat', c_long * MAX_PLATES),
        ('lUserParam1', POINTER(c_void_p)), ('lUserParam2', POINTER(c_void_p)),
        ('lUserParam3', POINTER(c_void_p)), ('lUserParam4', POINTER(c_void_p)),
        ('EliminateShadow', POINTER(c_void_p)),
        ('strPathCorrectedImage', c_char * MAX_FILE_PATH),
        ('vlCharacterPosition', c_long * MAX_PLATES * MAX_CHARACTERS * 4)
    ]
Exemplo n.º 27
0
class Lincons0Array(Structure):
    """
    typedef struct ap_lincons0_array_t {
      ap_lincons0_t* p;
      size_t size;
    } ap_lincons0_array_t;
    """

    _fields_ = [('p', POINTER(Lincons0)), ('size', c_size_t)]
Exemplo n.º 28
0
def c_digest(h_session, data_to_digest, digest_flavor, mech=None, extra_params=None):
    """Digests some data

    :param h_session: Current session
    :param data_to_digest: The data to digest, either a string or a list of strings. If this is a
    list a multipart operation will be used
    :param digest_flavor: The flavour of the mechanism to digest (MD2, SHA-1, HAS-160,
        SHA224, SHA256, SHA384, SHA512)
    :param mech: The mechanism to be used. If None a blank one with the
        digest_flavour will be used (Default value = None)
    :returns: The result code, a python string of the digested data

    """

    # Get mechanism if none provided
    if mech is None:
        if extra_params is None:
            mech = NullMech(digest_flavor).to_c_mech()
        else:
            mech = Mechanism(digest_flavor).to_c_mech()

    # Initialize Digestion
    ret = C_DigestInit(h_session, mech)
    if ret != CKR_OK:
        return ret, None

    # if a list is passed out do an digest operation on each string in the list, otherwise just
    # do one digest operation
    is_multi_part_operation = isinstance(data_to_digest, (list, tuple))

    if is_multi_part_operation:
        ret, digested_python_string = do_multipart_sign_or_digest(h_session, C_DigestUpdate,
                                                                  C_DigestFinal,
                                                                  data_to_digest)
    else:
        # Get arguments
        c_data_to_digest, c_digest_data_len = to_char_array(data_to_digest)
        c_data_to_digest = cast(c_data_to_digest, POINTER(c_ubyte))

        digested_data = AutoCArray(ctype=c_ubyte)

        @refresh_c_arrays(1)
        def _digest():
            """ Perform the digest operations
            """
            return C_Digest(h_session,
                            c_data_to_digest, c_digest_data_len,
                            digested_data.array, digested_data.size)

        ret = _digest()
        if ret != CKR_OK:
            return ret, None

        # Convert Digested data into a python string
        digested_python_string = string_at(digested_data.array, len(digested_data))

    return ret, digested_python_string
Exemplo n.º 29
0
def c_sign(h_session, h_key, data_to_sign, mechanism):
    """Signs the given data with given key and mechanism.

    .. note:: If data is a list or tuple of strings, multi-part operations will be used.

    :param int h_session: Session handle
    :param data_to_sign: The data to sign, either a string or a list of strings. If this is a list
         a multipart operation will be used (using C_...Update and C_...Final)

         ex:

             - "This is a proper argument of some data to use in the function"
             - ["This is another format of data this", "function will accept.",
                "It will operate on these strings in parts"]

    :param int h_key: The signing key
    :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function
        for possible values.
    :return: (retcode, python string of signed data)
    :rtype: tuple
    """

    mech = parse_mechanism(mechanism)

    # Initialize the sign operation
    ret = C_SignInit(h_session, byref(mech), CK_ULONG(h_key))
    if ret != CKR_OK:
        return ret, None

    # if a list is passed out do a sign operation on each string in the list,
    # otherwise just do one sign operation
    is_multi_part_operation = isinstance(data_to_sign, (list, tuple))

    if is_multi_part_operation:
        ret, signature_string = do_multipart_sign_or_digest(
            h_session, C_SignUpdate, C_SignFinal, data_to_sign)
    else:
        # Prepare the data to sign
        c_data_to_sign, plain_date_len = to_char_array(data_to_sign)
        c_data_to_sign = cast(c_data_to_sign, POINTER(c_ubyte))

        signed_data = AutoCArray(ctype=c_ubyte)

        @refresh_c_arrays(1)
        def _sign():
            """Perform the signing operation"""
            return C_Sign(h_session, c_data_to_sign, plain_date_len,
                          signed_data.array, signed_data.size)

        ret = _sign()
        if ret != CKR_OK:
            return ret, None

        signature_string = string_at(signed_data.array, len(signed_data))

    return ret, signature_string
Exemplo n.º 30
0
def c_decrypt(h_session, h_key, encrypted_data, mechanism):
    """Decrypt given data with the given key and mechanism.

    .. note:: If data is a list or tuple of strings, multi-part decryption will be used.

    :param int h_session: The session to use
    :param int h_key: The handle of the key to use to decrypt
    :param bytes encrypted_data: Data to be decrypted
    :param mechanism: See the :py:func:`~pycryptoki.mechanism.parse_mechanism` function
        for possible values.
    :returns: (Retcode, Python bytestring of decrypted data))
    :rtype: tuple
    """
    mech = parse_mechanism(mechanism)
    # Initialize Decrypt
    ret = C_DecryptInit(h_session, mech, CK_ULONG(h_key))
    if ret != CKR_OK:
        return ret, None

    # if a list is passed out do a decrypt operation on each string in the list, otherwise just
    # do one decrypt operation
    is_multi_part_operation = isinstance(encrypted_data, (list, tuple))

    if is_multi_part_operation:
        ret, python_data = do_multipart_operation(h_session, C_DecryptUpdate,
                                                  C_DecryptFinal,
                                                  encrypted_data)
    else:

        # Get the length of the final data
        # NOTE: The "Conventions for functions returning output in a variable-length buffer"
        # section of the PKCS#11 spec says that the length returned in this
        # case (no output buffer given to C_Decrypt) can exceed the precise
        # number of bytes needed. So the python string that's returned in the
        # end needs to be adjusted based on the second called to C_Decrypt
        # which will have the right length
        c_enc_data, c_enc_data_len = to_char_array(encrypted_data)
        c_enc_data = cast(c_enc_data, POINTER(c_ubyte))

        decrypted_data = AutoCArray(ctype=c_ubyte)

        @refresh_c_arrays(1)
        def _decrypt():
            """ Perform the decryption ops"""
            return C_Decrypt(h_session, c_enc_data, c_enc_data_len,
                             decrypted_data.array, decrypted_data.size)

        ret = _decrypt()
        if ret != CKR_OK:
            return ret, None

        # Convert the decrypted data to a python readable format
        python_data = string_at(decrypted_data.array, len(decrypted_data))

    return ret, python_data