Ejemplo n.º 1
0
def get_file_hash(filename):
    f = open(filename, "rb")
    handle = windows.utils.get_handle_from_file(f)

    size = DWORD(0)
    x = winproxy.CryptCATAdminCalcHashFromFileHandle(handle, ctypes.byref(size), None, 0)
    buffer = (BYTE * size.value)()
    try:
        x = winproxy.CryptCATAdminCalcHashFromFileHandle(handle, ctypes.byref(size), buffer, 0)
    except WindowsError as e:
        if e.winerror == 1006:
            # CryptCATAdminCalcHashFromFileHandle: [Error 1006]
            # The volume for a file has been externally altered so that the opened file is no longer valid.
            # (returned for empty file)
            return None
    return buffer
Ejemplo n.º 2
0
def calculate_file_hash(file_handle, hash_algorithm):
    cat_admin_handle = HANDLE()
    if hasattr(winproxy, 'CryptCATAdminAcquireContext2'):
        if winproxy.CryptCATAdminAcquireContext2(
                cat_admin_handle, DRIVER_ACTION_VERIFY, hash_algorithm, None,
                0) is False:
            return None, 0, None
    else:
        if winproxy.CryptCATAdminAcquireContext(
                cat_admin_handle, DRIVER_ACTION_VERIFY, 0) is False:
            return None, 0, None

    file_hash_length = DWORD(0)
    if hasattr(winproxy, 'CryptCATAdminCalcHashFromFileHandle2'):
        _ = winproxy.CryptCATAdminCalcHashFromFileHandle2(
            cat_admin_handle, file_handle, ctypes.byref(file_hash_length),
            None, 0)
        file_hash = (BYTE * file_hash_length.value)()
        try:
            ret = winproxy.CryptCATAdminCalcHashFromFileHandle2(
                cat_admin_handle, file_handle, ctypes.byref(file_hash_length),
                file_hash, 0)
        except WindowsError as ex:
            print(
                f"CryptCATAdminCalcHashFromFileHandle2() failed. ex={str(ex)}")
            return None, 0, None
    else:
        _ = winproxy.CryptCATAdminCalcHashFromFileHandle(
            file_handle, ctypes.byref(file_hash_length), None, 0)
        file_hash = (BYTE * file_hash_length.value)()
        try:
            ret = winproxy.CryptCATAdminCalcHashFromFileHandle(
                file_handle, ctypes.byref(file_hash_length), file_hash, 0)
        except WindowsError as ex:
            print(
                f"CryptCATAdminCalcHashFromFileHandle2() failed. ex={str(ex)}")
            return None, 0, None

    if ret is False:
        return None, 0, None
    else:
        return cat_admin_handle, file_hash_length.value, file_hash