The python module learns hashlib and the python module hashlib.
1. hashlib Overview
Encryption Services: 14. Cryptographic Services
Hashlib involves security hashing and message digest. It provides multiple different encryption algorithms, such as SHA1, shaloud, SHA256, SHA384, SHA512, and MD5.
Import hashlibm = hashlib. md5 () # create a hash object, md5 :( message-Digest Algorithm 5), obtain a 128-bit ciphertext print m #<md5 HASH object @ 000000000254ADF0> m. update ('beginman') # update the hash object with the string parameter print m. digest () # returns the abstract, which is the binary data string value print m. hexdigest () # returns the hexadecimal numeric string 0b28251e684dfbd9102f8b6f0281c0c5print m. digest_size #16 print m. block_size #64
Use new () to create a hash object in the 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 ('ripmd160 ', 'whe') print h2 #<ripemd160 HASH object @ 000000000271B9F0> h. update ('beginman') print h. hexdigest () #666fc5baa93a7fb207c5bfff03b67732 # equivalent s = hashlib. md5 () s. update ('beginman') print s. hexdigest () # 666fc5baa93a7fb207c5bfff03b67732print h2.hexdigest () #9c1185a5c5e9fc54612808977ee8f548b2258d31
Iii. common attributes
Print hashlib. algorithms # ('md5', 'sha1', 'shawei', 'sha256 ', 'sha384', 'sha512') lists all encryption algorithms.
Size of the hash generated by 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 as a string parameter. If the same hash object repeatedly calls this methodM. update (a); m. update (B)Is equivalentM. update (a + B).
Hash. digest ()
Returns the abstract, which is a string value of binary data,
Hash. hexdigest ()
Returns the abstract, which is a hexadecimal string value,
Hash. copy ()
Copy
Recently, in the file copy test, we need to compare the MD5 value after the file is copied to see if the copy is complete. Google and baidu both use the md5 module to read all files into the memory. When md5 is calculated, an error is reported if the file size exceeds 1 GB. The timespace brother provided the incremental MD5 calculation method and recorded it as follows:
#!/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()