开发者

python md5, d.update(strParam).hexdigest() returns NoneType.=, why?

>>> d = md5.new()
>>> d.update('a').hexdigest()
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'hexdigest'

this would work -

>>> d = md5.new()
>>> d.update('a')
>>> d.hexdigest()
'0cc175b9c0f1b6a831c399e269772661'

is there an explanation on s开发者_如何学Gohortening python code?


You can just do:

md5.new('a').hexdigest()

Paraphrased from the documentation:

new(arg) returns a new md5 object. If arg is present, the method call update(arg) is made.


But md5 is deprecated.
Use hashlib instead.

Edit:
There are also issues with md5 so depending on your purposes you might want to use a more-secure hash function, e.g. SHA-256:

import hashlib
hashlib.sha256('a').hexdigest()

Note that SHA-256 will take longer to compute so if you have time restrictions this may not be the way to go.


You want this:

import hashlib
hashlib.md5('a').hexdigest()

Note: Don't use plain MD5 for security.

  • If you're hashing passwords, use scrypt or bcrypt.
  • If you're authenticating a message, use an HMAC.
  • If you're checking file integrity, consider SHA2 or newer.


Well, since update had "no" return (default return in Python = None), calling update(arg).<anything> has to fail. Sometimes libraries will have return self as their last line of a method. If that were the case here, your first code sample would work.

With a semi-colon you can put all of your code on one line:

d = md5.new(); d.update('a'); d.hexdigest()

But it is generally discouraged.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜