深度阅读

How to Find Hash of File using Python

作者
作者
2023年08月22日
更新时间
10.81 分钟
阅读时间
0
阅读量

Sure, Here’s a Python program to find the hash of a file using the hashlib library:

import hashlib

# Open file for reading in binary mode ('rb')
with open('file.txt', 'rb') as f:

    # Instantiate a new SHA-256 hash object
    sha256_hash = hashlib.sha256()

    # Read the file in chunks and update the hash object
    for chunk in iter(lambda: f.read(4096), b''):
        sha256_hash.update(chunk)

# Get the hexadecimal representation of the hash digest
hash_hex = sha256_hash.hexdigest()

# Print the hash
print('The SHA-256 hash of file.txt is:', hash_hex)

Make sure to replace ‘file.txt’ with the name of your file. This program reads the file in chunks to avoid trying to load the entire file into memory at once, which can cause performance problems for large files.

This program uses the SHA-256 hash algorithm to calculate the hash digest of the file. You can use other hash algorithms such as SHA-1 or MD5 by instantiating a different hash object (e.g. hashlib.sha1() or hashlib.md5()).

I hope this helps you find the hash of a file using Python!

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。