所以我试图在 Python 中实现 MD5 算法。我已经阅读了大量的资料,来自 Rivest 的 ietf 的原始文件,但我仍然有一些我没有得到的东西:
所以这是代码:
import math
T=[]
for i in range(64):
el=hex(int(math.floor(pow(2,32)*math.fabs(math.sin(i+1)))))
el=el.rstrip('L')
T.append(el)
#print T
S=[7,12,17,22, 7,12,17,22, 7,12,17,22, 7,12,17,22,
5,9,14,20, 5,9,14,20, 5,9,14,20, 5,9,14,20,
4,11,16,23, 4,11,16,23, 4,11,16,23, 4,11,16,23,
6,10,15,21, 6,10,15,21, 6,10,15,21, 6,10,15,21]
A=0x67452301
B=0xefcdab89
C=0x98badcfe
D=0x10325476
msg="This is a message"
#M - working string
M=[]
for letter in msg:
M.append('{0:08b}'.format(ord(letter)))
AA,BB,CC,DD=A,B,C,D
for i in range(64):
if i<15:
F=(B and C) or((not B) and D)
g=i
elif i<31:
F=(D and B) or ((not D) and C)
g=(5*i+1)%16
elif i<47:
F= B and not C or D
else:
F=not C or(B or not D)
g=(7*i)%16
inter=hex(int(hex(A),16)+int(S[i]))
inter=int(inter.rstrip('L'),16)
F=hex((F+inter+int(M[g],2)%pow(2,32)))
A=D
F=F.rstrip('L')
#print F, 'F1'
F=int(F,16)<<S[i]
#print hex(F),'F2'
B=(B+F)%pow(2,32)
C=B
D=A
print 'AA',hex(AA),' ','BB',hex(BB),' ','CC',hex(CC),' ','DD',hex(DD)
AA+=A
BB+=B
CC+=C
DD+=D
print len(str(hex(AA)))+len(str(hex(BB)))+len(str(CC))+len(str(DD))
print ' ',str(hex(AA))[2:11],str(hex(BB))[2:12],str(hex(CC))[2:12]
FINAL= str(hex(AA)+hex(BB)+hex(CC)+hex(DD))
FINAL=FINAL.replace("0x","")
FINAL=FINAL.replace("L","")
问题是 AA、BB、CC、DD 的长度在十六进制的末尾(9,10 个字符)不同,这是不对的。我假设每当在 for 循环中移动时,这个数字就会显着增加。
问题是程序在哪里没有达到我的预期?我做错了什么?
任何帮助将不胜感激。