#!/usr/bin/env python3 # -*- coding:utf-8 -*- import threading from hashlib import sha256 from math import log import matplotlib.pyplot as plt
defentropy(wkList):# 计算信息熵 wkSet = set(wkList) rate = {} lenList = len(wkList) for k in wkSet: rate[k] = float(wkList.count(k)) / lenList return sum([-p * log(p, 2) for p in rate.values()])
# def gen_sha(n): # for i in range(n): # s = sha256(str(i).encode('utf-8')).hexdigest() # for j in range(64): # if j not in wkDict: # wkDict[j] = [s[j]] # else: # wkDict[j].append(s[j])
defgen_sha(_wkDict, start, stop): for _i in range(start, stop): s = sha256(str(_i).encode('utf-8')).hexdigest() for j in range(64): if j notin _wkDict: _wkDict[j] = [s[j]] else: _wkDict[j].append(s[j])
if __name__ == '__main__':
# gen_sha(1000) wkDict = {} # key: 某个十六进制位; value: 该位上的所有结果 threads = [] threadNum = 4 interval = int(1000000 / threadNum) for i in range(threadNum): threads.append(threading.Thread(target=gen_sha, args=(wkDict, i * interval, (i + 1) * interval))) [t.start() for t in threads] [t.join() for t in threads]
x = list(range(64)) y = [] for j in x: y.append(entropy(wkDict[j])) plt.plot(x, y) plt.xlim(0, 63) plt.ylim(3.9999, 4) plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置中文字体 plt.xlabel('十六进制位') plt.ylabel('信息熵') plt.show()