# 明文转二进制defbin_trans(mw):b =""for i in mw:c =bin(ord(i))[2:]whilelen(c)<8:c ='0'+ cb = b + creturn 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"+ appc = c + appreturn 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"+ aa ="0b"+ ac = a[2:2+n]a ="0b"+ a[2+n:]+ ca =int(a,2)a =hex(a)return a
# 非门defNot_func(a):a =int(a,16)a =bin(a)[2:]whilelen(a)<32:a ='0'+ ac =''for ch in a:if ch =='0':c = c +'1'else:c = c +'0'c ="0b"+ cc =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 =0x5A827999a = AA =hex((int(ROTL(A,5),16)+ ch(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)b = BB = ac = CC =hex(int(ROTL(b,30),16)%2**32)d = DD = cE = delif20<= t & t <=39:r =0x6ED9EBA1a = AA =hex((int(ROTL(A,5),16)+ parity(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)b = BB = ac = CC =hex(int(ROTL(b,30),16)%2**32)d = DD = cE = delif40<= t & t <=59:r =0x8F1BBCDCa = AA =hex((int(ROTL(A,5),16)+ maj(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)b = BB = ac = CC =hex(int(ROTL(b,30),16)%2**32)d = DD = cE = delif60<= t & t <=79:r =0xCA62C1D6a = AA =hex((int(ROTL(A,5),16)+ parity(B, C, D)+int(E,16)+int(w[t],16)+ r)%2**32)b = BB = ac = CC =hex(int(ROTL(b,30),16)%2**32)d = DD = cE = 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)