Brief introduction
Used for cryptographic related operations, instead of the MD5 module and the SHA module, mainly provides the SHA1,SHA224,SHA256,SHA384,SHA512,MD5 algorithm.
The MD5 and SHA modules have been discarded in python3, and the use of MD5 and SHA is briefly explained.
What is a digest algorithm?
Abstract algorithm, also known as hashing algorithm, hashing algorithm. It uses a function to convert any length of data into a data string of length headspace (usually represented by a 16-binary string) for encrypting related operations.
MD5 encryption
1 hash = hashlib.md5 ()2 hash.update ('admin'. Encode (' utf-8'))3print(hash.hexdigest ())4 21232f297a57a5a743894a0e4a801fc3
SHA1 encryption
1 hash = hashlib.sha1 ()2 hash.update ('admin'. Encode (' utf-8'))3print(hash.hexdigest ())4 d033e22ae348aeb5660fc2140aec35850c4da997
SHA256 encryption
1 hash = hashlib.sha256 ()2 hash.update ('admin'. Encode (' utf-8'))3print(hash.hexdigest ())4 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
sha384 encryption
1 hash = hashlib.sha384 ()2 hash.update ('admin'. Encode (' utf-8'))3print(hash.hexdigest ())4 9ca694a90285c034432c9550421b7b9dbd5c0f4b6673f05f6dbce58052ba20e4248041956ee8c9a2ec9f10290cdc0782
SHA512 encryption
1 hash = hashlib.sha512 ()2 hash.update ('admin'. Encode (' utf-8'))3print(hash.hexdigest ())4 c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8d E9077ec
Add some salt.
Although the above encryption algorithm is very powerful, but still has the flaw, through the collision library can reverse the solution. Therefore, it is necessary to add a custom key to the encryption algorithm to do encryption.
1 ###### MD5 Encryption ############2hash = HASHLIB.MD5 ('python'. Encode ('Utf-8'))3Hash.update ('Admin'. Encode ('Utf-8'))4 Print(Hash.hexdigest ())575b431c498b55557591f834af7856b9fHMAC encryption
The HMAC internally handles the key and content that we created after the encryption
1 ImportHMAC2H = hmac.new ('python'. Encode ('Utf-8'))3H.update ('HelloWorld'. Encode ('Utf-8'))4 Print(H.hexdigest ())5B3b867248bb4cace835b59562c39fd55Get the MD5 of a file
1 ImportHashlib2 defmd5sum (filename):3 """4 the MD5 value used to get the file5 :p Aram FileName: file name6 : Return:md5 yards7 """8 if notOs.path.isfile (filename):#if the checksum MD5 file is not a file, return an empty9 returnTenMyhash =hashlib.md5 () Onef = open (filename,'RB') A whileTrue: -b = F.read (8096) - if notB: the Break - Myhash.update (b) - f.close () - returnMyhash.hexdigest ()
Python---hashlib