# 明文转二进制defbin_trans(mw):
b =""for i in mw:
c =bin(ord(i))[2:]whilelen(c)<8:
c ='0'+ c
b = b + c
return b
# 对转换后的位字符串进行补位操作 并且转为16进制defsupplement(c):
length =len(c)%512if(length >448):
c = c +"1"for i inrange(1,512-length +448):
c = c +"0"elif(length <448):
c = c +"1"for i inrange(1,448-length):
c = c +'0'else:
c = c +'1'returnhex(int(c,2))# 附加长度值defappend(mw,c):
length =len(mw)# 附加明文的原长度
app =hex(8*length)[2:]while(len(app)<16):
app="0"+ app
c = c + app
return c
# 分为16个32比特的字defcut(w,c):for i inrange(0,16):
w.append("0x"+c[i*8:i*8+8])return w
# ROTL表示对32个比特的变量循环左移n比特defROTL(a,n):
a =int(a,16)
a =bin(a)
a = a[2:]whilelen(a)<32:
a ="0"+ a
a ="0b"+ a
c = a[2:2+n]
a ="0b"+ a[2+n:]+ c
a =int(a,2)
a =hex(a)return a
# 非门defNot_func(a):
a =int(a,16)
a =bin(a)[2:]whilelen(a)<32:
a ='0'+ a
c =''for ch in a:if ch =='0':
c = c +'1'else:
c = c +'0'
c ="0b"+ c
c =int(c,2)
c =hex(c)return c
#0 —— 19defch(x,y,z):
c =(int(x,16)&int(y,16))^(int(Not_func(x),16)&int(z,16))return c
#20 —— 39 60 —— 79defparity(x,y,z):
c =int(x,16)^int(y,16)^int(z,16)return c
#40 —— 59defmaj(x,y,z):
c =(int(x,16)&int(y,16))^(int(x,16)&int(z,16))^(int(y,16)&int(z,16))return c
if __name__=="__main__":#mw="Beijing University of Posts and Telecommunications"
mw="State Key Laboratory of Networking and Switching State Key Laboratory of Networking and Switching"# 初始散列值
A ='0x67452301'
B ='0xEFCDAB89'
C ='0x98BADCFE'
D ='0x10325476'
E ='0xC3D2E1F0'# 明文转二进制
c = bin_trans(mw)# 补位操作
c = supplement(c)# 附加长度值
c = append(mw, c)# 赋值给16个32比特的字
c = c[2:]
w =[]
w = cut(w,c)# 扩充W为80个 for i inrange(16,80):
app=int(w[i-3],16)^int(w[i-8],16)^int(w[i-14],16)^int(w[i-16],16)
app=ROTL(hex(app),1)
w.append(app)# for循环80次for t inrange(0,80):if0<= t & t <=19:
r =0x5A827999
a = A
A =hex((int(ROTL(A,5),16)+ ch(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)
b = B
B = a
c = C
C =hex(int(ROTL(b,30),16)%2**32)
d = D
D = c
E = d
elif20<= t & t <=39:
r =0x6ED9EBA1
a = A
A =hex((int(ROTL(A,5),16)+ parity(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)
b = B
B = a
c = C
C =hex(int(ROTL(b,30),16)%2**32)
d = D
D = c
E = d
elif40<= t & t <=59:
r =0x8F1BBCDC
a = A
A =hex((int(ROTL(A,5),16)+ maj(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)
b = B
B = a
c = C
C =hex(int(ROTL(b,30),16)%2**32)
d = D
D = c
E = d
elif60<= t & t <=79:
r =0xCA62C1D6
a = A
A =hex((int(ROTL(A,5),16)+ parity(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)
b = B
B = a
c = C
C =hex(int(ROTL(b,30),16)%2**32)
d = D
D = c
E = d
# 算出明文
A=hex((0x67452301+int(A,16))%2**32)
B=hex((0xEFCDAB89+int(B,16))%2**32)
C=hex((0x98BADCFE+int(C,16))%2**32)
D=hex((0x10325476+int(D,16))%2**32)
E=hex((0xC3D2E1F0+int(E,16))%2**32)
secret = A[2:]+B[2:]+C[2:]+D[2:]+E[2:]print("sha1加密后:",secret)