Detailed hashlib module in Python

A, hashlib profile

hashlib is a provider of some of the popular hash Python standard library (digest) algorithm. Which included algorithms md5, sha1, sha224, sha256, sha384, sha512 , etc.
What is the digest algorithm it? Digest algorithm, also known as hash algorithm, hash algorithm. It is through a function to convert data for any length of a fixed length data string (typically represented by a string of 16 hexadecimal). See more: hashlib - secure hash and message digest

Two, hashlib use

In this paper, hashlib the MD5 algorithm, for example, other sha224, sha256 and MD5 algorithm uses basically the same. If you want to see the other cases you can refer to my blog: achieve MD5, sha256, sha384, sha512, base64 encryption in python

1, common attributes

hashlib.algorithms
#列出所有加密算法

h.digest_size
#产生的散列字节大小。

h.block_size
#哈希内部块的大小

2, a common method

hash.new([arg])
# 创建指定加密模式的hash对象

hash.update(arg)
# 更新哈希对象以字符串参数。如果同一个hash对象重复调用该方法,m.update(a); m.update(b) 等价于 m.update(a+b)

hash.digest()
# 返回摘要,作为二进制数据字符串值。

hash.hexdigest()
# 返回摘要,作为十六进制数据字符串值

hash.copy()
# 复制

3, an example of use

# MD5 的使用
import hashlib

def jm_md5(password):
    m = hashlib.md5()  # 构建MD5对象
    m.update(password.encode(encoding='utf-8')) #设置编码格式 并将字符串添加到MD5对象中
    password_md5 = m.hexdigest()  # hexdigest()将加密字符串 生成十六进制数据字符串值
    return password, password_md5
    
g = jm_md5('123456')
print(g)

Three, hashlib features

1 digest algorithm in many places have a wide range of applications.
2, pay attention not digest algorithm encryption algorithm, encryption can not be used (because they can not digest by thrust reversers plain text), it can only be used to prevent tampering.
3, it can determine the characteristics of unidirectional calculated authentication password in plain text without storing passwords.

A good hash algorithm, will be able to achieve:
Reference blog

Fast forward: Given the plaintext and hash algorithm, for a limited time and limited resources can calculate the hash value.
Reverse problem: Given (a number of) the hash value, it is difficult (substantially impossible) Release expressly inverse in a finite time.
Enter sensitive: the original input information to modify that information, hash value generated should have looked very different.
Collision Avoidance: It's hard to find two different plaintext content, so that they are consistent with the hash value of the (conflict). I.e., for any two different data blocks, which is very unlikely that the same hash value; for a given block of data, and find that the same hash value is extremely difficult to block.

Fourth, the practical operation of the code

I can see other blog entries: achieve MD5, sha256, sha384, sha512, base64 encryption in python

1, for example sub-

import hashlib

# 一、在构建对象直接插入加密字符串
m1 = hashlib.md5('hello python'.encode(encoding='utf-8'))  # 构建MD5对象
print(m1.hexdigest())   # 结果为: e53024684c9be1dd3f6114ecc8bbdddc


# 二、通过update方法 往MD5对象中增加字符串参数
m2 = hashlib.md5()  # 构建MD5对象
m2.update('hello python'.encode(encoding='utf-8')) # 设置编码格式 并将字符串添加到MD5对象中
password_md5 = m2.hexdigest()
print(m2.hexdigest())   # 结果为 e53024684c9be1dd3f6114ecc8bbdddc


# 三、当数据量过过大时,可以分块摘要,例如:
m3 = hashlib.md5()
m3.update("hello ".encode("utf-8"))  # 注意:分块是空格也要保持一致
m3.update("python".encode("utf-8"))
print(m3.hexdigest())  # 结果为:e53024684c9be1dd3f6114ecc8bbdddc

# MD5是最常见的摘要算法,速度很快,生成结果是固定的128 bit字节,通常用一个32位的16进制字符串表示。

In three ways, the object constructed MD5 to pass parameters, parameter passing as long as the same character string, the result is the same as the last generated.
This shows that the hash algorithm is like a factory that receives raw materials you sent (can m.update () transport of raw materials for the plant), processed the returned product is the hash value. This is a summary of the characteristics of the algorithm, it is not an encryption algorithm, encryption can not be used (because they can not digest by thrust reversers plain text), it can only be used to prevent tampering.

2, case scenarios

hashlib module is mainly used, the user account password, the plaintext password encryption

import hashlib

USER_LIST = []
def pwd_Md5(password):
    password = password+'hello python'  # 字符串混淆加盐,可以设置更复杂一点
    return hashlib.md5(password.encode("utf-8")).hexdigest()


def register():
    print('**************用户注册**************')
    while True:
        user = input('请输入用户名:')
        if user.isalpha():
            break
    while True:
        password1 = input('请输入密码>>>:').strip()
        passwprd2 = input('请重复密码>>>:').strip()
        if password1 == passwprd2:
            password = pwd_Md5(password1)  # 将密码进行Md5加密
            break
        else:
            print('密码不正确,重新输入!')
    temp = {'username':user,'password':password}
    USER_LIST.append(temp)


def login():
    print('**************用户登陆**************')
    user = input('请输入用户名:')
    pwd = input('请输入密码:')

    for item in USER_LIST:  
        if item['username'] == user and item['password'] == pwd_Md5(pwd):
            return True

if __name__=='__main__':

    register()
    if login():
        print('登陆成功')
    else:
        print('登陆失败')


结果:
**************用户注册**************
请输入用户名:wuhan
请输入密码:123456
**************用户登陆**************
请输入用户名:小马过河
请输入密码:123456
登陆成功

Code analysis:
1, users need to log on with a password, the password must be encrypted to ensure that users of information security.
  1) hashlib encryption module may be used for encryption.
  2) can be written in the encrypted encryption function, to facilitate multiple call
  3) increase the complexity of the decrypted password, the code string to pay more. (Encryption algorithm, although still very powerful, but there are shortcomings, namely: the solution can counter hit by the library so it is necessary to encrypt passwords salted)

发布了46 篇原创文章 · 获赞 37 · 访问量 4513

Guess you like

Origin blog.csdn.net/weixin_42444693/article/details/104575153