出自:http://blog.iyunv.com/oychw/article/details/8921553
2013-05-13 磁针石
#承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.com qq 37391319 博客:http://blog.iyunv.com/oychw
#版权所有,转载刊登请来函联系
# 深圳测试自动化python项目接单群113938272深圳会计软件测试兼职 6089740
#深圳地摊群 66250781武冈洞口城步新宁乡情群49494279
#自动化测试和python群组: http://groups.google.com/group/automation_testing_python
#参考资料:《ThePython Standard Library by Example 2011》
# http://docs.python.org/2/howto/sockets.html
9.1 hashlib
hashlib用来替换md5和sha模块,并使他们的API一致。它由OpenSSL支持,支持如下算法:md5,sha1, sha224, sha256, sha384, sha512. 9.1.1 示例数据
importhashlib
lorem = ’’’Loremipsum dolor sit amet, consectetur adipisicing elit,
sed doeiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minimveniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip exea commodo consequat. Duis aute irure dolor in
reprehenderitin voluptate velit esse cillum dolore eu fugiat nulla
pariatur.Excepteur sint occaecat cupidatat non proident, sunt in
culpa quiofficia deserunt mollit anim id est laborum.’’’ 9.1.2 MD5
importhashlib
fromhashlib_data import lorem
h =hashlib.md5()
h.update(lorem)
print h.hexdigest()
执行结果:
$ pythonhashlib_md5.py
1426f365574592350315090e295ac273
9.1.3 SHA1
importhashlib
fromhashlib_data import lorem
h =hashlib.sha1()
h.update(lorem)
printh.hexdigest()
执行结果:
$ pythonhashlib_sha1.py
8173396ba8a560b89a3f3e2fcc024b044bc83d0a
9.1.4 new
使用new可以指定加密的类型。
#end_pymotw_header
importhashlib
import sys
try:
hash_name = sys.argv[1]
exceptIndexError:
print 'Specify the hash name as the firstargument.'
else:
try:
data = sys.argv[2]
except IndexError:
from hashlib_data import lorem as data
h =hashlib.md5()
h.update(lorem)
all_at_once =h.hexdigest()
defchunkize(size, text):
"Return parts of the text insize-based increments."
start = 0
while start < len(text):
chunk = text[start:start+size]
yield chunk
start += size
return
h =hashlib.md5()
for chunk inchunkize(64, lorem):
h.update(chunk)
line_by_line= h.hexdigest()
print 'All atonce :', all_at_once
print 'Lineby line:', line_by_line
print'Same :', (all_at_once ==line_by_line)
执行结果:
$ pythonhashlib_update.py
All at once :1426f365574592350315090e295ac273
Line by line:1426f365574592350315090e295ac273
Same : True
参考资料:
hashlib(http://docs.python.org/library/hashlib.html) The standard librarydocumentation
for thismodule.
Voidspace:IronPython and hashlib
(www.voidspace.org.uk/python/weblog/arch_d7_2006_10_07.shtml#e497)A
wrapper for hashlibthat works with IronPython.
hmac (page473) The hmac module.
OpenSSL(http://www.openssl.org/) An open source encryption toolkit.
zlib包含adler32 和 crc32哈希。