verify.py 1.12 KB
Newer Older
1 2
import hashlib

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
def feed_file(h, f):
    """Feed data read from an open file into the hashlib instance."""

    while True:
        data = f.read(65536)
        if len(data) == 0:
            # end of file
            break
        h.update(data)

def feed_file_path(h, path):
    """Feed data read from a file (to be opened by this function) into the hashlib instance."""

    with open(path, 'rb') as f:
        feed_file(h, f)

19 20
def file_digest(algorithm, path):
    """Calculate the digest of a file and return it in hexadecimal notation."""
21

22
    h = algorithm()
23 24
    feed_file_path(h, path)
    return h.hexdigest()
25

26 27 28 29
def guess_digest_algorithm(digest):
    l = len(digest)
    if l == 32:
        return hashlib.md5
30 31 32 33
    elif l == 40:
        return hashlib.sha1
    elif l == 64:
        return hashlib.sha256
34 35
    else:
        return None
36 37 38 39

def verify_file_digest(path, expected_digest):
    """Verify the digest of a file, and return True if the digest matches with the given expected digest."""

40 41 42
    algorithm = guess_digest_algorithm(expected_digest)
    assert(algorithm is not None)
    return file_digest(algorithm, path) == expected_digest