python 代码 加密 哈希_python加密模块hashlib

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

>>> import hashlib

>>> m = hashlib.md5()

>>> m.update("Nobody inspects")

>>> m.update(" the spammish repetition")

>>> m.digest()

'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'

>>> m.hexdigest()

'bb649c83dd1ea5c9d9dec9a18df0ffe9'

对以上代码的说明:

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

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

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

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

5.加密后的二进制结果

6.十六进制结果

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

>>>print hashlib.new("md5", "Nobody inspects the spammish repetition").hexdigest()

'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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值