• Python hashlib模块 (主要记录md5加密)


    python提供了一个进行hash加密的模块:hashlib

    下面主要记录下其中的md5加密方式(sha1加密一样把MD5换成sha1)

    1. >>> import hashlib  
    2.   
    3. >>> m = hashlib.md5()  
    4.   
    5. >>> m.update("Nobody inspects")  
    6.   
    7. >>> m.update(" the spammish repetition")  
    8.   
    9. >>> m.digest()  
    10.   
    11. 'xbbdx9cx83xddx1exa5xc9xd9xdexc9xa1x8dxf0xffxe9'  
    12.   
    13. >>> m.hexdigest()  
    14.   
    15. 'bb649c83dd1ea5c9d9dec9a18df0ffe9'  



    对以上代码的说明:

    1.首先从python直接导入hashlib模块

    2.调用hashlib里的md5()生成一个md5 hash对象

    3.生成hash对象后,就可以用update方法对字符串进行md5加密的更新处理

    4.继续调用update方法会在前面加密的基础上更新加密

    5.加密后的二进制结果

    6.十六进制结果

    如果只需对一条字符串进行加密处理,也可以用一条语句的方式:

    1. >>>print hashlib.new("md5", "Nobody inspects the spammish repetition").hexdigest()  
    2.   
    3. 'bb649c83dd1ea5c9d9dec9a18df0ffe9'  

    引用官方文档部分:

    The following values are provided as constant attributes of the hash objects returned by the constructors:

    hash.digest_size

    The size of the resulting hash in bytes.

    hash.block_size

    The internal block size of the hash algorithm in bytes.

    A hash object has the following methods:

    hash.update(arg)

    Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).

    hash.digest()

    Return the digest of the strings passed to the update() method so far. This is a string of digest_size bytes which may contain non-ASCII characters, including null bytes.

    hash.hexdigest()

    Like digest() except the digest is returned as a string of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.

    hash.copy()

    Return a copy (“clone”) of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring.

  • 相关阅读:
    爬虫实践-微博关键词搜索抓取
    爬虫实践-拉勾网测试经理JD抓取【2018.05.15】
    爬虫实践--租房信息查找
    服务器python发送mail无法发出问题
    我的面试流程梳理
    字典树模板(前缀查找、整串查找)
    搬运工程 启动!
    开始收集模板啦!
    WPS表格中不能输入中文 or其他
    ubunt命令
  • 原文地址:https://www.cnblogs.com/zhaojia-dream/p/3792128.html
Copyright © 2020-2023  润新知