python使用ctypes加载C编写的dll库,该dll功能是计算字符串或文件哈希值,算法为SM3。可确保该dll无误,在机器上测试过可计算出正确值。
编写的是一个网络程序,Client向Server发送文件与其文件哈希值。Server接收文件后进行哈希值检验。
print(sm3().sm3_file("test.txt"))
print(sm3().cal_sm3("123456"))
class sm3:
def __init__(self):
self.sm3dll = cdll.LoadLibrary('./sm3.dll')
def return_res(self, out):
return out.value.hex().upper()
def sm3_file(self, path):
path = create_string_buffer(path.encode(), len(path))
buf = (c_char * 32)()
self.sm3dll.sm3_file(path, buf)
return self.return_res(buf)
def cal_sm3(self, buf):
output = (c_char * 32)()
inp = create_string_buffer(buf.encode(), len(buf))
self.sm3dll.sm3(inp, len(buf), output)
return self.return_res(output)
def getfile(client, data):
global mistake_hash #空值
size = int(data["file_size"])
bk_hash = data["hash"]
temp = data["temp"]
base = int(data["base"])
cache_path = os.getcwd() + "/cache/bk_cache%s.dat" % temp
cache_path = cache_path.replace("\\", "/")
flag = False
error_time = 0
while True:
bk_cache = open(cache_path, "wb")
cnt = 0
while (cnt + base) < size:
if flag:
time.sleep(0.2)
buf = client.recv(base)
bk_cache.write(buf)
cnt += base
time.sleep(0.0005)
if (size - cnt) > 0:
buf = client.recv(size - cnt)
bk_cache.write(buf)
time.sleep(0.0005)
bk_cache.close()
recvhash = sm3().sm3_file(cache_path)
while recvhash == mistake_hash:
# 卡死在这
recvhash = sm3().sm3_file(cache_path)
if bk_hash == recvhash:
client.send(json.dumps({"code": 1}).encode())
break
else:
client.send(json.dumps({"code": 0}).encode())
flag = True
error_time += 1
if error_time >= 3:
break
client.close()
一开始认为是IO处理未完成就开始计算,因此利用sleep在计算前确保IO处理完成,但是没用。
计算出正确的哈希值
你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答
本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。
因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。