Python's Hashlib module

Source: Internet
Author: User

First, Hashlib basic use

The Hashlib module in Python is used for hashing or MD5 encryption, and this encryption is irreversible, so this algorithm is called the Digest algorithm. It supports all the algorithms provided by the OpenSSL library, including MD5, SHA1, sha224, SHA256, sha512, and so on.

Common Properties and methods:

Algorithms: List all cryptographic algorithms (' MD5 ', ' SHA1 ', ' sha224 ', ' sha256 ', ' sha384 ', ' sha512 ')

Digesti_size: The size of the resulting hash bytes

MD5 ()/SHA1 (): Create a Hash object that MD5 or SHA1 encryption mode

Update (ARG): The hash object is updated with a string parameter, if the method is called repeatedly by the same has object, as follows: M.update (a); M.update (b) is equal to M.update (A+B)

Digest (): Returns the digest as a binary data string value

Hexdigest (): Returns the digest as a hexadecimal data string value

Copy (): Copy

Here is a simple example of cryptography:

Import HASHLIBM = hashlib.md5 () m.update (' How to useMD5'. Encode ('utf-8')) M.update (' inpython hashlib'. Encode ('utf-8'))print m.hexdigest () 

The return values are as follows:

9f97604918a2e86bfcc4aea5c35a4c8b

The following example is used to calculate the file MD5 value:

#!/usr/bin/env python#Coding:utf-8ImportHashlibImportSysDefMain ():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: Span style= "COLOR: #0000ff" >while TRUE:BLK = Fp.read (4096) # every read 4kb if not Blk: break M.update (BLK) print M.hexdigest (), Filenameif __name__ = =  "__main__: Main ()         

Second, the Hashlib application scenario

Abstract algorithms are typically applied to information about the user's account password that the site stores. By default, the account password that we insert into the database is saved in clear text. In this case, once the database is compromised, all users ' passwords are leaked directly, and the text is saved, and the webmaster can view the user's password directly, which is not safe. So we can encrypt it directly after we get the password that the user entered. The encrypted string is then stored in the database. This way, the next time the user logs on, the password entered by the user is encrypted, then compared to the encrypted string stored in the database, and if so, the password is correct.

Of course, the above method is much safer than storing passwords in plaintext. In some scenarios, however, users often set passwords to be especially simple. This way, if the database is compromised, hackers can use a simple password attempt to complete the matching of the encrypted string. To solve this problem, we usually need to "add salt" to the password. As follows:

def get_md5 (password):      m = hashlib.md5 ()    m.update (password)    return m.hexdigest ()  def'the-salt') db = {}def Register (Username,password): db[username] = username Db[password] = calc_md5 (password)            

This way, as long as the ' The-salt ' part is not leaked, there is no way to reverse the user's simple password.

However, there is still a problem, that is, multiple users of the password may be duplicated, so that in the database will appear the same encryption string. We know that, in general, the user's username is definitely not the same. Let's assume that the user's user name does not change. We can use the user's user name to do salt processing, as follows:

def Clc_md5 (username,password):    'the-salt')   

Python's Hashlib module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.