Apr 10, 2009

Python hashlib

支持 the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm
接口是统一的
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()

md5 128bit
sha1 160bit (git 使用 sha1)

>>> import hashlib
>>> m = hashlib.md5()
>>> m.update(b"Today is very warm. We would like to go swimming")
>>> m.hexdigest()
'52020cb97950d732bed382c9609bbd8a'
>>> len(m.hexdigest())
32
>>> m.digest_size
16
生成 md5
import hashlib
import sys

if len(sys.argv)>1:
 f = open(sys.argv[1],'rb')
 if f:
  m = hashlib.md5()
  m.update(f.read())
  print(m.hexdigest())
  
 f.close()
连续update:
m.update(str1)
m.update(str2)
生成 str1+str2 的 md5
所以如果对大文件进行hash,可以边读边update

0 comments: