• python hashlib模块


    hashlib用来替换md5和sha模块,并使他们的API一致。它由OpenSSL支持,支持如下算法:

    md5,sha1, sha224, sha256, sha384, sha512。

    示例一:

    import hashlib
    m = hashlib.md5() #创建hash对象,md5:(message-Digest Algorithm 5)消息摘要算法,得出一个128位的密文
    print m #<md5 HASH object @ 02B93250>
    m.update('python') #更新哈希对象,以字符串为参数
    print m.digest() #返回摘要,作为二进制数据字符串值
    print m.hexdigest() #返回摘要,作为十六进制数据字符串值 23eeeb4347bdd26bfc6b7ee9a3b755dd
    print m.digest_size #16,结果hash的大小,产生的散列的字节大小
    print m.block_size #64,hash内部块的大小,The internal block size of the hash algorithm in bytes

    print hashlib.md5('python').hexdigest()#简略写法 23eeeb4347bdd26bfc6b7ee9a3b755dd

    m1=m.copy()#复制
    print m #<md5 HASH object @ 02B93250>
    print m1 #<md5 HASH object @ 02B93200>

    示例二:使用new()创建指定加密模式的hash对象

    import hashlib
    h = hashlib.new('md5')
    print h #<md5 HASH object @ 029F3200>
    h.update('python')
    print h.hexdigest() #23eeeb4347bdd26bfc6b7ee9a3b755dd
    print h.block_size,h.digest_size
    print hashlib.new('md5','python').hexdigest() #简略写法 23eeeb4347bdd26bfc6b7ee9a3b755dd
    #等效
    h1 = hashlib.md5()
    h1.update('python')
    print h1.hexdigest() #23eeeb4347bdd26bfc6b7ee9a3b755dd
    print h1.block_size,h1.digest_size
    print hashlib.md5('python').hexdigest() #简略写法 23eeeb4347bdd26bfc6b7ee9a3b755dd
    #列出所有加密算法
    print hashlib.algorithms#('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')

    当前要执行的test.py文件:


    import hashlib
    from data import s
    h =hashlib.md5()
    h.update(s)
    all_at_once=h.hexdigest()
    #增量更新,文件太大的时候,可以分多次读入
    def chunkmd5(size,text):
    '''''Return parts of the text in size-based increments.'''
    start=0
    while start<len(text):
    chunk=text[start:start+size]
    yield chunk
    start+=size

    h1=hashlib.md5()
    for chunk in chunkmd5(64,s):
    h1.update(chunk)

    all_at_many_time= h1.hexdigest()
    print 'All at once :',all_at_once
    print 'All at many time:',all_at_many_time
    print 'the two is same?:', (all_at_once ==all_at_many_time)

    结果:

    All at once     : fda376c90e12c5f0ec0c8dc86b056aa3
    All at many time: fda376c90e12c5f0ec0c8dc86b056aa3
    the two is same?: True

  • 相关阅读:
    win7+Apache 设置域名指向本地文件夹
    JavaScript 函数式编程
    JS防抖动
    13 个最佳 JavaScript 数据网格库
    js笔试-接收get请求参数
    这10道javascript笔试题你都会么
    60行JavaScript代码俄罗斯方块
    先少谈点人工智能好吗?
    gulp+webpack构建配置
    Gulp和webpack的区别,是一种工具吗?
  • 原文地址:https://www.cnblogs.com/jack1989/p/9850598.html
Copyright © 2020-2023  润新知