The Hashlib module is a package that appears later in the python2.5, which mainly involves security and encryption. and Hashlib get OpenSSL "support", which supports all the algorithms provided by OpenSSL library, including MD5, SHA1, sha224, SHA256, sha512, etc. Detailed usage, which can be viewed through Pydoc hashlib, combines two simple examples to see its usage.
First, get the MD5 value of a string
For example, when the user password in the Web site is involved, the password of the administrator account is often MD5 encrypted and then stored in the database. Assuming that the Admin user has a password of 361way, you can do the following with Python code:
>>> Import Hashlib
>>> m = hashlib.md5 ()
>>> m.update ("361way")
>>> M.hexdigest ()
4ac40dc92ce5bc8bbe3d28849f0be1e9
When you view help, there is also a digest method. The difference between the two is as follows:
Md5.digest () returns a 16-byte digest, generated by a string passed to update, with no ASCII characters
Md5.hexdigest () returns a summary in the form of 16, with 32 bits
Again, the 361way character above, the result of the execution of M.digest () is as follows:
>>> M.digest ()
' J\xc4\r\xc9,\xe5\xbc\x8b\xbe= (\X84\X9F\X0B\XE1\XE9 '
If the Hashlib method is very skilled, the above code can be directly abbreviated as follows:
>>> Import Hashlib
>>> hashlib.md5 ("361way"). Hexdigest ()
' 4ac40dc92ce5bc8bbe3d28849f0be1e9 '
The SHA algorithm, however, simply replaces the MD5 method with the corresponding Sha method. The difference is that the SHA algorithm executes a longer result, which is slower than the MD5 calculation process, so MD5 is often used to store the user's password. SHA1 is often used as a digital signature.
Second, confirm the MD5 value of the document
Often we confirm that the file has been modified by the MD5 value before and after the file. The code in this section implements the same functionality as the Linux md5sum instruction. The specific code is as follows:
#!/usr/bin/python
#encoding =utf-8
Import IO
Import Sys
Import Hashlib
Import string
Def printusage ():
Print (' Usage: [python] pymd5sum.py <filename> ')
def main ():
if (sys.argv.__len__ () ==2):
#print (Sys.argv[1])
m = Hashlib.md5 ()
File = Io. FileIO (sys.argv[1], ' R ')
bytes = File.read (1024)
while (bytes!= B "):
M.update (bytes)
bytes = File.read (1024)
File.close ()
#md5value = ""
Md5value = M.hexdigest ()
Print (md5value+ "\ T" +sys.argv[1])
#dest = io. FileIO (sys.argv[1]+). Checksum.md5 ", ' W ')
#dest. Write (Md5value)
#dest. Close ()
Else
Printusage ()
Main ()
The specific code I deposited on my GitHub page.
To avoid excessive file size and high memory usage, read the file in 1024 byte.
Other related modules are HMAC, which is mainly used for password message signing and verification.