20. hashlib module

First, how to use the module

  • Hashlib reference module in Python
  • Create a hash object, use the constructor hash algorithm named or generic constructor
  • Use hash object to call update () method to fill an object
  • Calls digest () or hexdigest () method to get digest (encrypted result)

Second, the actual use of the module

1. md5_obj = hashlib.md5() 或 md5_obj = hashlib.new("md5") -> md5可以替换为其他的哈希类型
2. md5.update(arg) -> 将字节对象arg填充到hashlib对象中,arg通常为要加密的字符串
3. md5.digest() -> 返回加密结果 ,它是一个字节对象,长度为md5.digest_size
4. md5.hexdigest() -> 返回加密结果,它是一个字符串对象,长度为md5.digest_size*2,只包含16进制数字

注意事项:
(1) update()方法需要接收的参数是一个字节对象
(2) 常用的一些算法主要有sha1, sha224, sha256, sha384, sha512, md5等算法
(3) sha1算法比较早,是不能暴力破解的
import hashlib

Plaintext = "Hello world"
# 实例化一个hash对象
md5_obj = hashlib.md5()
# 对需要操作的明文操作->编程16进制
result = md5_obj.hexdigest()
print(result)

>d41d8cd98f00b204e9800998ecf8427e
加盐 - hashlib.md5("salt".encode("utf-8"))

import hashlib

# md5_obj = hashlib.md5(b"with salt")
md5_obj = hashlib.md5("with salt".encode("utf-8"))
md5_obj.update("hello world".encode("utf-8"))
result = md5_obj.hexdigest()
print(result)

Example 1. a

When the user login authentication, usually user account and password into the file, and the user password is not stored in a file as it is, but the real number of conversion by means of md5 algorithm used here, according to its derivation is irreversible advantage, therefore, the general not easy to get to crack user passwords.

import hashlib

def get_md5(Plaintext):
    md5_obj = hashlib.md5()
    md5_obj.update(Plaintext.encode("utf-8"))
    result = md5_obj.hexdigest()
    return result

username = input("username:")
password = input("password:")

with open("userInfo") as f:
    for line in f:
        usr, pwd = line.strip().split('|')
        if username == usr and get_md5(password) == pwd:
            print("登录成功!")
            break

    else:
        print("登录失败!")

2. Example Two

When reading the file, not the best f.readline (). The reason: the entire contents of the file is read into memory, so that larger memory footprint, thus wasting resources. It is suggested to use a file handle for loop operation, the contents of the file in an internal read line by line

import hashlib
def get_file_md5(file_path):
    md5_obj = hashlib.md5()
    with open('file_path', encoding = 'utf-8') as f:
        for line in f:
            md5_obj.update(line.encode('utf-8'))
        ret = md5_obj.hexdigest()
    return ret

3. Example Three

The above document describes its share of less byte, if the downloaded file is a video or a large, this time, the form should be read in the form of rb, bytes are read out, in addition, this is similar to a video file, not press OK to read, can not read out the one-time - using getSize () method, each taking a fixed byte or a large video file

import os
import hashlib
def get_file_md5(file_path, buffer = 1024):
    md5_obj = hashlib.md5()
    file_size = os.path.getsize(file_path)
    with open(file_path, 'rb') as f:
        while file_size:
            content = f.read(buffer)
            file_size -= len(content)
            md5_obj.update(content)    # 文件是rb形式传输,所以不需要'utf-8'
    return md5_obj.hexdigest()

4. Example Four

import 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("user.txt", mode="r", encoding="utf-8") as f:
        for line in f:
            name, password = line.strip().split("|")
            # 登录的时候验证用户名以及加密的密码跟之前保存的是否一样
            if user == name and password == md5(pwd):
                return True

def register(user, pwd):  # 注册的时候把用户名和加密的密码写进文件,保存起来
    with open("user.txt", mode="a", encoding="utf-8") as f:
        msg = user + "|" + md5(pwd) + "\n"
        f.write(msg)

i = input("1表示登录,2表示注册").strip()
if i == "2":
    user = input("用户名:")
    pwd = input("密码:")
    register(user, pwd)
elif i == "1":
    user = input("用户名")
    pwd = input("密码:")
    r = log(user, pwd)  # 验证用户名和密码
    if r == True:
        print("登录成功")
    else:
        print("登录失败")
else:
    print("输入不合法")

Guess you like

Origin www.cnblogs.com/hq82/p/12457304.html
Recommended