官术网_书友最值得收藏!

How to do it...

In the following steps, we will see how to obtain the hash of a file:

  1. Begin by importing the libraries and selecting the desired file you wish to hash:
import sys
import hashlib

filename = "python-3.7.2-amd64.exe"
  1. Instantiate the MD5 and SHA256 objects, and specify the size of the chunks we will be reading:
BUF_SIZE = 65536
md5 = hashlib.md5()
sha256 = hashlib.sha256()
  1. We then read in the file in chunks of 64 KB and incrementally construct our hashes:
with open(filename, "rb") as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
md5.update(data)
sha256.update(data)
  1. Finally, print out the resulting hashes:
print("MD5: {0}".format(md5.hexdigest()))
print("SHA256: {0}".format(sha256.hexdigest()))

This results in the following output:

MD5: ff258093f0b3953c886192dec9f52763
SHA256: 0fe2a696f5a3e481fed795ef6896ed99157bcef273ef3c4a96f2905cbdb3aa13

主站蜘蛛池模板: 汨罗市| 竹溪县| 景宁| 平舆县| 阜阳市| 满城县| 玛曲县| 铜鼓县| 修文县| 伊金霍洛旗| 舞钢市| 太保市| 广水市| 宁城县| 石柱| 湖南省| 九台市| 洱源县| 万全县| 江北区| 新宾| 鹿泉市| 泰来县| 洛宁县| 郓城县| 澄江县| 彩票| 高州市| 会理县| 龙陵县| 泸溪县| 郁南县| 焦作市| 万载县| 新巴尔虎右旗| 宜丰县| 义乌市| 鄂伦春自治旗| 阜平县| 泸水县| 安陆市|