10cm有多长:Python二进制处理 SHA-1算法

来源:百度文库 编辑:中财网 时间:2024/04/29 22:25:19
#--coding=gbk--
#===============================================================================
# Copyright (c) 2011 - zj
# python 2.7.1
#===============================================================================
import array
import struct
import hashlib
h0 = 0x67452301
h1 = 0xEFCDAB89
h2 = 0x98BADCFE
h3 = 0x10325476
h4 = 0xC3D2E1F0
h  = 0xFFFFFFFF
def hexdigest(string):
s=""
for c in string:
s=s+str(hex(ord(c)>>4))[2:3]+str(hex(ord(c)&0xF))[2:3]
return s
def leftrotate(word,bits):
return ((((word) << (bits)) & 0xFFFFFFFF) | ((word) >> (32 - (bits))))
mfile=open("E:/a.txt","r")
message=mfile.read()
mfile.close()
#Pre-processing:
#append the bit '1' to the message
#append k bits '0', where k is the minimum number >= 0 such that the resulting message
#    length (in bits) is congruent to 448 (mod 512)
#append length of message (before pre-processing), in bits, as 64-bit big-endian integer
l=len(message)
i=zeroByte=((448-l*8%512-8)%512)/8
ppmessage=message+'\x80'
while i>0:
ppmessage=ppmessage+'\x00'
i=i-1
ppmessage=ppmessage+struct.pack(">Q",l*8)
s=array.array('L')
try:
s.fromstring(ppmessage)
except  ValueError :
print "Pre-processing error"
l=s.tolist()
for i in range(len(l)/16):
w=[]
for word in l[i*16:i*16+16]:
#into big-endian
w.append(struct.unpack(">L",struct.pack("L",word))[0])
assert(len(w)==16)
#Extend the sixteen 32-bit words into eighty 32-bit words:
for j in range(16,80):
w.append(leftrotate(w[j-3]^ w[j-8] ^ w[j-14] ^ w[j-16],1))
assert(len(w)==80)
a = h0
b = h1
c = h2
d = h3
e = h4
for j in range(0,80):
if 0 <= j and j <= 19:
#f =(b&c)|((~b)&d)&h
f=d ^ (b & (c ^ d)) &h
k = 0x5A827999
else:
if 20<=j and j<=39:
f = b^c^d&h
k = 0x6ED9EBA1
else:
if 40 <= j and j <= 59:
f = (b & c) | (b & d) | (c & d)&h
k = 0x8F1BBCDC
else:
if 60 <= j and j <= 79:
f = b ^ c ^ d&h
k = 0xCA62C1D6
temp = leftrotate(a,5) + f + e + k + w[j]&h
e = d
d = c
c = leftrotate(b,30)
b = a
a = temp
#Add this chunk's hash to result so far:
h0 = h0 + a &h
h1 = h1 + b &h
h2 = h2 + c &h
h3 = h3 + d &h
h4 = h4 + e &h
#Produce the final hash value (big-endian):
digest = struct.pack(">5L",h0,h1,h2, h3,h4)
shaf=open("E:/sha.txt","w")
shaf.write(digest)
#与内置算法作比较
print hexdigest(digest)
print hashlib.sha1(message).hexdigest()
http://zh.wikipedia.org/wiki/SHA_%E5%AE%B6%E6%97%8F