MD5 message-digest Algorithm (MD5 message-digest Algorithm) is a widely used password hash function that produces a 128-bit (16-byte) hash value to ensure complete and consistent transmission of information. MD5, the most common digest algorithm, is fast and produces a fixed 128 bit result, usually represented by a 32-bit hexadecimal string.

Hashlib introduction

Python's Hashlib provides common digest algorithms, such as MD5, SHA1, and so on. The algorithm is also called hashing algorithm and hashing algorithm. It uses a function to convert data of arbitrary length into a data string of fixed length16Base string representation). In python3 standard library, md5 module has been removed, and all hash encryption algorithms are stored in hashlib standard library, such as SHA1, SHA224, SHA256, SHA384, SHA512, md5 algorithm, etc.Copy the code

Get md5 values for string and file md5 values

import hashlib
 
 
def get_md5_from_str(data_str):
    """Get md5 value of string :param data_str: :return:"""
 
    restult = hashlib.md5(data_str.encode(encoding='utf-8'). Hexdigest () # Returns the digest as a hexadecimal data string value # restult = hashlib.md5(data_str.encode(encoding='utf-8').digest() # returns the digest as a binary data string valuereturn restult
 
 
def get_md5_from_file(file_path):
    """Obtain the MD5 value of the file :param file_path: file path: return: MD5 value"""
    m = hashlib.md5()
    a_file = open(file_path, 'rb'(a_file.read()) a_file.close()return m.hexdigest()
 
 
if __name__ == "__main__":
    str_temp = 'shenshang'
    print(get_md5_from_str(str_temp))
    print(get_md5_from_file('./get_md5.py'))
Copy the code