Home >Backend Development >Python Tutorial >python module learning hashlib
1. Overview of hashlib
Involving encryption services: 14. Cryptographic Services
Among them, hashlib involves secure hashing and message digest, providing multiple different encryption algorithm interfaces, such as SHA1, SHA224, SHA256, SHA384, SHA512, md5, etc.
import hashlib m = hashlib.md5() #创建hash对象, md5:(message-Digest Algorithm 5)消息摘要算法,得出一个128位的密文 PRint m #<md5 HASH object @ 000000000254ADF0> m.update('BeginMan')#更新哈希对象以字符串参数 print m.digest() #返回摘要,作为二进制数据字符串值 print m.hexdigest() #返回十六进制数字字符串 0b28251e684dfbd9102f8b6f0281c0c5print m.digest_size #16 print m.block_size #64
Use new() to create a hash object with a specified encryption mode
new(name, string='') """ Return a new hashing object using the named algorithm; optionally initialized with a string. """ h = hashlib.new('md5')print h #<md5 HASH object @ 000000000260BDB0>h2 = hashlib.new('ripemd160','what')print h2 #<ripemd160 HASH object @ 000000000271B9F0>h.update('beginman')print h.hexdigest() #666fc5baa93a7fb207c5bfff03b67732#等效s = hashlib.md5() s.update('beginman')print s.hexdigest() #666fc5baa93a7fb207c5bfff03b67732print h2.hexdigest() #9c1185a5c5e9fc54612808977ee8f548b2258d31 三、常用属性 print hashlib.algorithms #('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') 列出所有加密算法 print h.digest_size #16 产生的散列的字节大小。 print h.block_size #64 The internal block size of the hash algorithm in bytes.
IV. Common methods
hash.update(arg)
Update the hash object with string parameters. If the same hash object calls this method repeatedly, Then m.update(a); m.update(b) is equivalent to m.update(a+b).
hash.digest()
returns the digest as a binary data string value,
hash.hexdigest()
Returns the digest as a hexadecimal data string value,
hash.copy()
Copy
Recently in the test file copy test, it is necessary to perform the MD5 value of the file after copying Compare to see if the copy is complete. Google and Baidu both use the md5 module to read all files into memory. When calculating md5, an error occurs when calculating files exceeding 1G in size. Brother timespace gave a method for incrementally calculating MD5, record it:
#!/usr/bin/env pythonimport hashlibimport sys def main(): if len(sys.argv) != 2: sys.exit('Usage: %s file' % sys.argv[0]) filename = sys.argv[1] m = hashlib.md5() with open(filename, 'rb') as fp: while True: blk = fp.read(4096) # 4KB per block if not blk: break m.update(blk) print m.hexdigest(), filenameif __name__ == '__main__': main()
The above is the content of learning hashlib in python module. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!