## 2012年2月10日 星期五

### [Python Std Library] 14.1. hashlib — Secure hashes and message digests

Preface :
New in version 2.5.
Source code: Lib/hashlib.py

Usage :

>>> import hashlib
>>> m = hashlib.sha1()
>>> m.update("Nobody inspects".encode())
>>> m.update(" the spammish repetition".encode())
>>> m.digest()
b'S\x1b\x07\xa0\xf5\xb6dw\xa2\x17B\xd2\x82qv&OK\xbf\xe2'
>>> m.digest_size
20
>>> m.block_size
64

>>> hashlib.sha1("Nobody inspects the spammish repetition".encode()).hexdigest()
'531b07a0f5b66477a21742d2827176264f4bbfe2'

>>> h = hashlib.new('sha1')
>>> h.update('Nobody inspects the spammish repetition'.encode())
>>> h.hexdigest()
'531b07a0f5b66477a21742d2827176264f4bbfe2'

- DigestCal.py :
1. import hashlib
2.
3. def CalDigest( hexStr, sep=None ,type="sha1"):
4.     """
5.     Calculate the digest/hash value of given hex string based on different algorithm indicated by 'type'.
6.     """
7.     hexStr = ''.join(hexStr.split(" "))
8.     if (len(hexStr)%2) == 0:
9.         hobj = hashlib.new(type)
10.         hobj.update(HexToByte(hexStr).encode())
11.         digHex = hobj.hexdigest().upper()
12.         if sep:
13.             bytes = []
14.             for i in range(0, len(digHex), 2):
15.                 bytes.append(digHex[i:i+2])
16.             return sep.join(bytes)
17.         else:
18.             return digHex
19.     else:
20.         print("\t[Info] Illegal Hex String={0}".format(hexStr))
21.
22. def HexToByte( hexStr ):
23.     """
24.     Convert a string hex byte values into a byte string. The Hex Byte values may
25.     or may not be space separated.
26.     """
27.     # The list comprehension implementation is fractionally slower in this case
28.     #
29.     #    hexStr = ''.join( hexStr.split(" ") )
30.     #    return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \
31.     #                                   for i in range(0, len( hexStr ), 2) ] )
32.
33.     bytes = []
34.
35.     hexStr = ''.join( hexStr.split(" ") )
36.
37.     for i in range(0, len(hexStr), 2):
38.         bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )
39.
40.     return ''.join( bytes )

>>> import DigestCal # 組入模組 DigestCal
>>> DigestCal.CalDigest("01 02 03") # 計算 byte 0x01 0x02 0x03 三個 bytes 的 SHA1
'7037807198C22A7D2B0807371D763779A84FDFCF'
>>> DigestCal.CalDigest("01 02 03", sep=' ') # 使用 ' ' 區隔每一個 byte
'70 37 80 71 98 C2 2A 7D 2B 08 07 37 1D 76 37 79 A8 4F DF CF'
>>> DigestCal.CalDigest("01 02 03", sep='-', type='md5') # 改用 MD5 來計算, 並使用 '-' 區隔每一個 byte
'52-89-DF-73-7D-F5-73-26-FC-DD-22-59-7A-FB-1F-AC'

Supplement :
Byte to Hex and Hex to Byte String Conversion (Python recipe)

## 關於我自己

Where there is a will, there is a way!