The MD5 checksum data fingerprint Python3 Comparative

MD5 message digest algorithm (English: MD5 Message-Digest Algorithm), a widely used cryptographic hash function , can produce a 128-bit (16 byte ) hash value (hash value), for ensuring the transmission of information complete and consistent. MD5 by American cryptographers Ron Rivest , in 1992 public (Ronald Linn Rivest) designed to replace the MD4 algorithm.

Outline

Small amount MD5 checksum calculation made by the hash function can generate data "fingerprint" of any data, i.e., we can use the MD5 message digest, or to data compression, the data is easy to verify the integrity and correctness of the data comparison . Because two different files is almost impossible to have the same MD5 hash value of any file on a non-malicious changes will lead to changes in its MD5 hash. So MD5 hash common language file integrity checking, especially in testing the accuracy of file transfer, disk error or other circumstances documents.

MD5

We use the built-in Python module hashlib to complete the implementation and use of MD5.

import hashlib

m = hashlib.md5()
# 假设文件内容
src = 'I like Python'
m.update(src.encode('utf-8'))
print(m.hexdigest())
复制代码

Sample results:

17008b7417701b0c233b999d20c13f1d
复制代码

File validation

Assuming that there are two existing files, we need to verify that these two documents as

import hashlib


def out_md5(src):
    # 简单封装
    m = hashlib.md5()
    m.update(src.encode('utf-8'))
    return m.hexdigest()


with open('1.txt', 'r') as f:
    src = f.read()
    m1 = out_md5(src)
    print(m1)

with open('2.txt', 'r') as f:
    src = f.read()
    m2 = out_md5(src)
    print(m2)

if m1 == m2:
    print(True)
else:
    print(False)
复制代码

Sample results:

bb0c1b519a0a2b8e6c74703e44538c60
43cb091db43a710d85ce45fb202438cd
False
复制代码

Reproduced in: https: //juejin.im/post/5cfe624ae51d4556d86c7a9c

Guess you like

Origin blog.csdn.net/weixin_33910460/article/details/91463570