本文主要是介绍密码学:基于python支持448位输入的sha-1算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#只支持448比特
#寄存器的初始值
H0 = 0x67452301
H1 = 0xefcdab89
H2 = 0x98badcfe
H3 = 0x10325476
H4 = 0xc3d2e1f0
#分组的所有字
W=[]
#常数值Kt
def K(t):
if 0 <= t and t<=19:
return 0x5a827999
elif 20 <= t and t<=39:
return 0x6ed9eba1
elif 40 <= t and t<=59:
return 0x8f1bbcdc
elif 60 <= t and t<=79:
return 0xca62c1d6
#f基本逻辑函数
def F(t,b,c,d):
if 0 <= t and t<=19:
return (b&c) | (~b&d)
elif 20 <= t and t<=39:
return b^c^d
elif 40 <= t and t<=59:
return (b&c) | (b&d) | (c&d)
elif 60 <= t and t<=79:
return b^c^d
#比特字Wt的值
def Wt(t):
a = W[t-16]^W[t-14]^W[t-8]^W[t-3]
W[t] = S(1,a)
return W[t]
#循环左移k
def S(k,a):
return ((a>>32-k) | (a<<k) & Sum())
#求32位1
def Sum():
s = 0;
for i in range(32):
s = s + 2**i
return s
#分割M
def dM(m):
for i in range(16):
W[i] = (m>>32*(15-i)) & Sum()
if __name__ == "__main__":
A = H0
B = H1
C = H2
D = H3
E = H4
i=0
m = 0
M = input()
L = 8*len(M)
for ch in M:
m = m*(2**8)+ord(ch)
if L < 448:
m = m*2+1
#添加填充位
m = m*2**(447 - L)
#添加长度
m = m*2**64 + L
for i in range(80):
W.append(i)
dM(m)
for i in range(16,80):
Wt(i)
print(hex(m))
#80步循环的寄存器
for t in range(80):
temp = (S(5,A)%(2**32)+W[t]%(2**32)+E+F(t,B,C,D)+K(t)%(2**32))%2**32
E = D
D = C
C = S(30,B)
B = A
A = temp
print(t,': ',hex(A),' ',hex(B)," ",hex(C)," ",hex(D)," ",hex(E))
A = (A + H0)%2**32
B = (B + H1)%2**32
C = (C + H2)%2**32
D = (D + H3)%2**32
E = (E + H4)%2**32
isha = A*2**(4*32) + B*2**(3*32) + C*2**(2*32) + D*2**32 + E
sha = hex(isha)
print("消息摘要:",str(sha)[2:])
这篇关于密码学:基于python支持448位输入的sha-1算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!