资源简介
利用python3实现了国密SM3和国密SM4算法,一共有两个文件SM3.py和sm4.py
代码片段和文件信息
IV=[0x7380166f0x4914b2b90x172442d70xda8a0600
0xa96f30bc0x163138aa0xe38dee4d0xb0fb0e4e]
T_j = []
for i in range(0 16):
T_j.append(0)
T_j[i] = 0x79cc4519
for i in range(16 64):
T_j.append(0)
T_j[i] = 0x7a879d8a
#输入为32比特,分为4块,每块为8比特的数
#输出为32比特输入对应的大整数
def hex2int_32(key_data):
tmp_data = int((key_data[0] << 24) | (key_data[1] << 16) | (key_data[2] << 8) | (key_data[3]))
return tmp_data
def str2byte(msg): # 字符串转换成byte数组
ml = len(msg)
msg_byte = []
msg_bytearray = msg.encode(‘utf-8‘)
for i in range(ml):
msg_byte.append(msg_bytearray[i])
return msg_byte
def byte2str(msg): # byte数组转字符串
ml = len(msg)
str1 = b““
for i in range(ml):
str1 += b‘%c‘ % msg[i]
return str1.decode(‘utf-8‘)
def hex2byte(msg): # 16进制字符串转换成byte数组
ml = len(msg)
if ml % 2 != 0:
msg = ‘0‘+ msg
ml = int(len(msg)/2)
msg_byte = []
for i in range(ml):
msg_byte.append(int(msg[i*2:i*2+2]16))
return msg_byte
def byte2hex(msg): # byte数组转换成16进制字符串
ml = len(msg)
hexstr = ““
for i in range(ml):
hexstr = hexstr + (‘%02x‘% msg[i])#‘%02x‘% msg[i]表示将msg[i]用两位十六进制数表示
return hexstr
#输入为96比特,三个分组,每个32比特
#输出为32比特
def FF(XYZj):
if j<=15:
return X^Y^Z
else:
return (X&Y)|(X&Z)|(Y&Z)
def GG(XYZj):
if j<=15:
return X^Y^Z
else:
return (X&Y)|(~X&Z)
#输入为一个32比特的整数
#输出为循环左移n比特后的32比特整数
def SHL(x n):
n = n % 32
xx = int(int(x << n) & 0xffffffff)
return xx
def ROTL(x n):
n = n % 32
xx = SHL(x n)
yy = xx | int((x >> (32 - n)) & 0xffffffff)
return yy
#输入为32比特的字,输出也为32比特
def P_0(X):
return X^(ROTL(X9))^(ROTL(X17))
def P_1(X):
return X^(ROTL(X15))^(ROTL(X23))
#对原始消息msg做填充,使其二进制表示的长度为512的倍数
#msg的元素为8比特整数,
def sm3_padding(msg):
M=msg
len1=len(msg)
reserve1=len1 % 64
M.append(0x80)
reserve1 = reserve1 + 1
range_end = 56
if reserve1 > range_end:
range_end = range_end + 64
for i in range(reserve1 range_end):
M.append(0x00)
#上述过程,在二进制表示下,含义为先添加了一个‘1’,又添加了一些0
bit_length = (len1) * 8
bit_length_str = [bit_length % 0x100]
for i in range(7):
bit_length = int(bit_length / 0x100)
bit_length_str.append(bit_length % 0x100)
for i in range(8):
M.append(bit_length_str[7-i])
#上述过程的含义是,添加msg长度的二进制表示
return M
#定义压缩函数CFCF的输入分为两块,第一部分为256比特,分为32块,每块为8比特整数
#第二部分为512比特,分为64块,每块为8比特整数
#输出为256比特,分为32块,每块为8比特整数
def CF(V_iB_i):
W=[]
for i in range(16):
data=0
tmp_data = int((B_i[4*i] << 24) | (B_i[4*i+1] << 16) | (B_i[4*i+2] << 8) | (B_i[4*i+3]))
W.append(tmp_data)
for j in range(1668):
W.append(0)
W[j]=P_1(W[j-16]^W[j-9]^(ROTL(W[j-3]15)))^(ROTL(W[j-13]7))^W[j-6]
W1=[]
for k in range(64):
W1.append(0)
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 4976 2018-12-25 17:00 python实现sm3sm4\sm3.py
文件 4982 2018-12-23 10:03 python实现sm3sm4\sm4.py
目录 0 2018-12-27 15:14 python实现sm3sm4
----------- --------- ---------- ----- ----
9958 3
评论
共有 条评论