search
HomeBackend DevelopmentPython TutorialA deep dive into the hashlib module in python


The content of this article is to share with you an in-depth understanding of the hashlib module in python. It has a certain reference value. Friends in need can refer to it

hashlib


hashlib mainly provides character encryption functions, integrates md5 and sha modules, and supports md5, sha1, sha224, sha256, sha384, sha512 and other algorithms

Specific application

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#pyversion:python3.5
#owner:fuzj

import hashlib

# ######## md5 ########

string = "beyongjie"
md5 = hashlib.md5()
md5.update(string.encode('utf-8'))     #注意转码
res = md5.hexdigest()
print("md5加密结果:",res)

# ######## 

sha1 ########sha1 = hashlib.sha1()
sha1.update(string.encode('utf-8'))
res = sha1.hexdigest()
print("sha1加密结果:",res)

# ######## 

sha256 ########sha256 = hashlib.sha256()
sha256.update(string.encode('utf-8'))
res = sha256.hexdigest()
print("sha256加密结果:",res)

# ######## 

sha384 ########sha384 = hashlib.sha384()
sha384.update(string.encode('utf-8'))
res = sha384.hexdigest()
print("sha384加密结果:",res)

# ######## 
sha512 ########sha512= hashlib.sha512()
sha512.update(string.encode('utf-8'))
res = sha512.hexdigest()
print("sha512加密结果:",res)

Output result:

md5加密结果: 0e725e477851ff4076f774dc312d4748
sha1加密结果: 458d32be8ea38b66300174970ab0a8c0b734252f
sha256加密结果: 1e62b55bfd02977943f885f6a0998af7cc9cfb95c8ac4a9f30ecccb7c05ec9f4
sha384加密结果: e91cdf0d2570de5c96ee84e8a12cddf16508685e7a03b3e811099cfcd54b7f52183e20197cff7c07f312157f0ba4875b
sha512加密结果: 3f0020a726e9c1cb5d22290c967f3dd1bcecb409a51a8088db520750c876aaec3f17a70d7981cd575ed4b89471f743f3f24a146a39d59f215ae3e208d0170073

Note: The string type encrypted by hashlib is binary encoding. Directly encrypting the string will report the following error:

sha1 = hashlib.sha1()
sha1.update(string)
res = sha1.hexdigest()print("sha1加密结果:",res)


TypeError: Unicode-objects must be encoded before hashing

You can use encode to convert

shaa1 = hashlib.sha1()
shaa1.update(string.encode('utf-8'))
res = shaa1.hexdigest()print("sha1采用encode转换加密结果:",res)

Or use byte to convert to binary

shab1 = hashlib.sha1()
shab1.update(bytes(string,encoding='utf-8'))
res = shab1.hexdigest()print("sha1采用byte转换的结果:",res)

The above output:

sha1采用encode转换加密结果: 458d32be8ea38b66300174970ab0a8c0b734252f
sha1采用byte转换的结果: 458d32be8ea38b66300174970ab0a8c0b734252f

Here is a code that uses md5 to log in to the website and encrypt the password after registration. Basic examples to deepen understanding

#hashlib简单使用
def md5(arg):#这是加密函数,将传进来的函数加密
    md5_pwd = hashlib.md5(bytes('abd',encoding='utf-8'))
    md5_pwd.update(bytes(arg,encoding='utf-8'))
    return md5_pwd.hexdigest()#返回加密的数据
def log(user,pwd):#登陆时候时候的函数,由于md5不能反解,因此登陆的时候用正解
    with open('db','r',encoding='utf-8') as f:
        for line in f:
            u,p=line.strip().split('|')
            if u ==user and p == md5(pwd):#登陆的时候验证用户名以及加密的密码跟之前保存的是否一样
                return True
def register(user,pwd):#注册的时候把用户名和加密的密码写进文件,保存起来
    with open('db','a',encoding='utf-8') as f:
        temp = user+'|'+md5(pwd)
        f.write(temp)
 
i=input('1表示登陆,2表示注册:')
if i=='2':
    user = input('用户名:')
    pwd =input('密码:')
    register(user,pwd)
elif i=='1':
    user = user = input('用户名:')
    pwd =input('密码:')
    r=log(user,pwd)#验证用户名和密码
    if r ==True:
        print('登陆成功')
    else:
        print('登陆失败')
else:
    print('账号不存在')

Here we only briefly write down the registration and login of a user


Common methods

  • hash.update(arg) updates the hash object with string parameters. Note: If the same hash object calls this method repeatedly, 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("第一次a加密:",res)

m.update('b'.encode('utf-8'))
res = m.hexdigest()print("第二次b加密:",res)


m1 = hashlib.md5()
m1.update('b'.encode('utf-8'))
res = m1.hexdigest()print("b单独加密:",res)

m2 = hashlib.md5()
m2.update('ab'.encode('utf-8'))
res = m2.hexdigest()print("ab单独加密:",res)


输出结果:
第一次a加密: 0cc175b9c0f1b6a831c399e269772661
第二次b加密: 187ef4436122d1cc2f40dc2b92f0eba0
b单独加密: 92eb5ffee6ae2fec3ad71c777531578f
ab单独加密: 187ef4436122d1cc2f40dc2b92f0eba0
  • hash.digest() returns the digest as a binary data string value,

  • hash.hexdigest() Returns the digest as a hexadecimal data string value,

  • ##hash.copy() Copy

AdvancedEncryption

Although the above encryption algorithm is still very powerful, it still has flaws, that is, it can be reversed through credential stuffing. Therefore, it is necessary to add a custom key to the encryption algorithm before performing encryption.

low = hashlib.md5()
low.update('ab'.encode('utf-8'))
res = low.hexdigest()print("普通加密:",res)

high = hashlib.md5(b'beyondjie')
high.update('ab'.encode('utf-8'))
res = high.hexdigest()print("采用key加密:",res)

输出结果:
普通加密: 187ef4436122d1cc2f40dc2b92f0eba0
采用key加密: 1b073f6b8cffe609751e4c98537b7653

 

附加HMAC-SHA1各语言版本实现

在各大开放平台大行其道的互联网开发潮流中,调用各平台的API接口过程中,无一例外都会用到计算签名值(sig值)。而在各种计算签名的方法中,经常被采用的就是HMAC-SHA1,现对HMAC-SHA1做一个简单的介绍:

        HMAC,散列消息鉴别码,基于密钥的Hash算法认证协议。实现原理为:利用已经公开的Hash函数和私有的密钥,来生成固定长度的消息鉴别码;

        SHA1、MD5等Hash算法是比较常用的不可逆Hash签名计算方法;

        BASE64,将任意序列的8字节字符转换为人眼无法直接识别的符号编码的一种方法;

        各个语言版本的实现为:

        Python版:       
               import hmac
                             
               import hashlib
                             
               import base64

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

Token:即接口的key

data:要加密的数据

        PHP版:
              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版:
              echo -n '3f88a95c532bea70' | openssl dgst -hmac '123' -sha1 -binary | base64

The above is the detailed content of A deep dive into the hashlib module in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools