Example of using the hashlib module in python: pythonhashlib

Source: Internet
Author: User
Tags hmac

Example of using the hashlib module in python: pythonhashlib

We have previously introduced an article on Python encryption: An Example of Python encryption. Let's take a look at the usage example of the hashlib module in python.


Hashlib mainly provides the character encryption function. It integrates md5 and sha modules and supports algorithms such as md5, sha1, shaloud, sha256, sha384, and sha512.
Specific Application

#! /Usr/bin/env python #-*-coding: UTF-8-*-# pyversion: python3.5 # owner: fuzjimport hashlib ######### md5 ######## string = "beyongjie" md5 = hashlib. md5 () md5.update (string. encode ('utf-8') # note that transcoding res = md5.hexdigest () print ("md5 encryption Result:", res) ######### sha1 ####### sha1 = hashlib. sha1 () sha1.update (string. encode ('utf-8') res = sha1.hexdigest () print ("sha1 encrypted Result:", res) ######### sha256 ######## sha256 = hashlib. sha256 () sha256.update (string. encode ('utf-8') res = sha256.hexdigest () print ("sha256 encrypted Result:", res) ######### sha384 ####### sha384 = hashlib. sha384 () sha384.update (string. encode ('utf-8') res = sha384.hexdigest () print ("sha384 encrypted Result:", res) ######### sha512 ######## sha512 = hashlib. sha512 () sha512.update (string. encode ('utf-8') res = sha512.hexdigest () print ("sha512 encrypted Result:", res)

Output result:

Md5 encryption result: 0e725e477851ff4076f774dc312d4748sha1 encryption result: 458d32be8ea38b66300174970ab0a8c0b734252fsha256 encryption result: Encrypt

Note: If the string type of hashlib is binary, the following error is returned when the string is directly encrypted:

Sha1 = hashlib. sha1 () sha1.update (string) res = sha1.hexdigest () print ("sha1 encrypted Result:", res) TypeError: Unicode-objects must be encoded before hashing

Encode conversion is supported.

Shaa1 = hashlib. sha1 () shaa1.update (string. encode ('utf-8') res = shaa1.hexdigest () print ("sha1 uses encode to convert encryption results:", res)

Or use byte to convert to binary.

Shab1 = hashlib. sha1 () shab1.update (bytes (string, encoding = 'utf-8') res = shab1.hexdigest () print ("sha1 uses byte conversion results:", res)

The above output:

Sha1 adopts encode conversion encryption result: 458d32be8ea38b66300174970ab0a8c0b734252fsha1 adopts byte Conversion Result: 458d32be8ea38b66300174970ab0a8c0b734252f

Common Methods

Hash. update (arg) updates the hash object with string parameters. Note: if the same hash object repeatedly calls this method, m. update (a); m. update (B) is equivalent to m. update (a + B). See the following example.

M = hashlib. md5 () m. update ('A '. encode ('utf-8') res = m. hexdigest () print ("first a :", res) m. update ('B '. encode ('utf-8') res = m. hexdigest () print ("second B encryption:", res) m1 = hashlib. md5 () m1.update ('B '. encode ('utf-8') res = m1.hexdigest () print ("B separately encrypted:", res) m2 = hashlib. md5 () m2.update ('AB '. encode ('utf-8') res = m2.hexdigest () print ("AB encrypted separately:", res) output result: First Time aencrypted: 0cc175b9c0f1b6a831c399e269772661 second time B encrypted: 187ef4436122d1cc2f40dc2b92f0eba0b encryption: 92eb5ffee6ae2fec3ad71c777531578fab encryption: 187ef4436122d1cc2f40dc2b92f0eba0

Hash. digest () returns the abstract, which is a string value of binary data,

Hash. hexdigest () returns the abstract, which is the string value of the hexadecimal data,

Hash. copy () replication

Advanced Encryption

Although the above encryption algorithms are still very powerful, they have some drawbacks, that is, they can be reversed by Credential stuffing. Therefore, it is necessary to add a custom key to the encryption algorithm and then encrypt it.

Low = hashlib. md5 () low. update ('AB '. encode ('utf-8') res = low. hexdigest () print ("common encryption:", res) high = hashlib. md5 (B 'beyondjie ') high. update ('AB '. encode ('utf-8') res = high. hexdigest () print ("key encryption:", res) output result: normal encryption: 187ef4436122d1cc2f40dc2b92f0eba0 key encryption: Encrypt

Additional HMAC-SHA1 versions available in various languages

In the popular Internet Development Trends of major open platforms, the signature value (sig value) is used to call APIs of various platforms without exception ). In a variety of signature calculation methods, often used is the HMAC-SHA1, The HMAC-SHA1 is a simple introduction:

HMAC, Hash message authentication code, and key-based Hash algorithm authentication protocol. Implementation principle: generate a fixed-length message authentication code using public Hash Functions and private keys;

SHA1, MD5, and other Hash algorithms are commonly used to calculate irreversible Hash signatures;

BASE64 is a method that converts 8-byte characters of any sequence into symbols that cannot be directly recognized by human eyes;

The implementation of each language version is:

Python version:

       import hmac       import hashlib       import base64       hmac.new(Token,data,hashlib.sha1).digest().encode('base64').rstrip()

Token: the key of the interface.

Data: data to be encrypted

PHP version:

       base64_encode(hash_hmac("SHA1",clientStr,Token , true))

C ++ (Openssl ):

        HMAC( EVP_sha1(),          /*key data*/ strKey.data(),          /*key len*/ strKey.size(),          /*data */(unsigned char*) strRandom.data(),          /*data len*/ strRandom.size(), digest, &digest_len))

Shell version:

       echo -n '3f88a95c532bea70' | openssl dgst -hmac '123' -sha1 -binary | base64


The above is all the content about the hashlib module usage example in python. I hope it will be helpful to you. If you are interested, you can continue to refer to this site: Some Thoughts on Python caused by _ dict _ and dir (), and three errors to be avoided when using Python variables, thank you for your support!

Related Article

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.