Gangmax Blog

hashlib in Python

今天我又仔细看了看”CSDN泄密用户数据“里面的信息,忽然想知道在python里面如何对字符串做hash操作,就查到了这篇文章,按照里面的代码,稍作修改[1]如下即可:

1
2
3
4
5
6
7
8
>>> print(hashlib.new("md5",b"this is a test.").hexdigest())
09cba091df696af91549de27b8e7d0f6
>>> print(hashlib.new("sha1",b"this is a test.").hexdigest())
7728f8eb7bf75ec3cc49364861eec852fc814870
>>> print(hashlib.new("sha256",b"this is a test.").hexdigest())
aaae6f4e850e064ee0cbce6ac8fc6cab0a17f0ce112aaedba122fbc782d8251b
>>> print(hashlib.new("sha512",b"this is a test.").hexdigest())
640ada87d87eb01725b8b6293598c47193b891f13f9bc6b845fbd347f7f7b2e2df14f3698df00e6a8a6187a5d8373bdad824b8a10f0da80642ab32c338985e26

这样写也可以:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> test_str="this is a test"
>>> type(test_str)
<class 'str'>
>>> bytes = test_str.encode("utf-8")
>>> type(bytes)
<class 'bytes'>
>>> bytes = "this is a test.".encode("utf-8")
>>> print(hashlib.new("md5", bytes).hexdigest())
09cba091df696af91549de27b8e7d0f6
>>> print(hashlib.new("sha1", bytes).hexdigest())
7728f8eb7bf75ec3cc49364861eec852fc814870
>>> print(hashlib.new("sha256", bytes).hexdigest())
aaae6f4e850e064ee0cbce6ac8fc6cab0a17f0ce112aaedba122fbc782d8251b
>>> print(hashlib.new("sha512", bytes).hexdigest())
640ada87d87eb01725b8b6293598c47193b891f13f9bc6b845fbd347f7f7b2e2df14f3698df00e6a8a6187a5d8373bdad824b8a10f0da80642ab32c338985e26

结论:在python里面做字符串的hash还是很简单的。

注[1]:在原文的例子中,使用的代码用的是Python2.6之前的风格,在Python2.7和Python3.0下不能正常工作:原因是新的Python引入了”bytes array”的概念,将原来的”string”概念分成了包含”characters sequence”和”bytes sequence”,其中的后者就是”bytes array”。两种概念具体可以参考这里

1
print hashlib.new("md5", "JGood is a handsome boy").hexdigest()  

Comments