当前位置: 首页 > 工具软件 > MurmurHash > 使用案例 >

murmurhash2算法python3版本

闻法
2023-12-01

在翻译加密代码时遇到这个murmurhash2算法了,网上找了几个现成的加密结果对不上,自己手动对照原加密翻译了一般python3版本的。

# -*- coding: utf-8 -*-
# @ Time    : 2021/8/26 14:40
# @Note: Please do not use this program for illegal uses.

import ctypes


def unsigned_right_shitf(num, bit):
    return ctypes.c_uint32(num).value >> bit


def c_int32(int_num):
    return ctypes.c_int32(int_num).value


def murmurhash2(e, timestamp):
    array_len = len(e)
    f = c_int32(timestamp ^ array_len)
    o = 0
    while array_len >= 4:
        v2 = c_int32(255 & e[o])
        o += 1
        v3 = c_int32((c_int32(255 & e[o])) << 8)
        o += 1
        v4 = c_int32((c_int32(255 & e[o])) << 16)
        o += 1
        v5 = c_int32(c_int32((255 & e[o])) << 24)
        n = c_int32(c_int32(c_int32(v2 | v3) | v4) | v5)
        v1 = c_int32(65535 & n)
        n = 1540483477 * v1 + c_int32((c_int32(1540483477 * (c_int32(n >> 16)) & 65535)) << 16)

        n = c_int32(c_int32(n) ^ c_int32(unsigned_right_shitf(n, 24)))
        n = 1540483477 * (c_int32(65535 & n)) + c_int32((c_int32(1540483477 * (c_int32(n >> 16)) & 65535)) << 16)

        j1 = 1540483477 * (c_int32(65535 & f))
        j2 = c_int32((1540483477 * (c_int32(f >> 16)) & 65535) << 16)
        f = c_int32((j1 + j2) ^ n)

        o += 1
        array_len -= 4
    f = c_int32(f)

    def case1(ff):
        ff = c_int32(ff ^ (c_int32(255 & e[o])))
        return 1540483477 * (c_int32(65535 & ff)) + c_int32((c_int32(1540483477 * (c_int32(ff >> 16)) & 65535)) << 16)

    def case2(ff):
        return c_int32(ff ^ c_int32((c_int32(255 & e[o + 1])) << 8))

    def case3(ff):
        return c_int32(ff ^ c_int32((c_int32(255 & e[o + 2])) << 16))

    if array_len == 1:
        f = case1(f)
    if array_len == 2:
        f = case1(case2(f))
    if array_len == 3:
        f = case1(case2(case3(f)))

    f = c_int32(f ^ unsigned_right_shitf(f, 13))
    f = 1540483477 * (c_int32(65535 & f)) + c_int32((c_int32(1540483477 * unsigned_right_shitf(f, 16) & 65535)) << 16)
    f = c_int32(f ^ unsigned_right_shitf(f, 15))
    print("result:", f)
    return c_int32(unsigned_right_shitf(f, 0) ^ 1540483477)



if __name__ == '__main__':
    murmurhash2(list(b'123abc'), int(time.time()*1000))

 类似资料: