Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the md5 hash of a tempfile in python?

Tags:

python

I'm getting an attachment from an email Message object and creating a tempfile like so:

import tempfile

with tempfile.NamedTemporaryFile() as temp:
    temp.write(payload.get_payload(decode=True))

Is it possible to get the md5 out of this tempfile or do I have to save it to disk and then get the md5? Something like so would be what I'm aiming for:

import hashlib
print(hashlib.md5(temp).hexdigest())

But I run into this error

TypeError: object supporting the buffer API required
like image 876
ssh.to.2501 Avatar asked Aug 30 '18 05:08

ssh.to.2501


People also ask

How do I find the hash of a file in Python?

Source Code to Find HashHash functions are available in the hashlib module. We loop till the end of the file using a while loop. On reaching the end, we get empty bytes object. In each iteration, we only read 1024 bytes (this value can be changed according to our wish) from the file and update the hashing function.

What does Tempfile mean in Python?

Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.


1 Answers

When you call the hashlib.md5 command it does expect a string like object instead of a file handle. But guess what you already have that. So there is no need to read it back from the file.

import tempfile
import hashlib

with tempfile.NamedTemporaryFile() as temp:
    data = payload.get_payload(decode=True)
    temp.write(data)
    print(hashlib.md5(data).hexdigest())
like image 155
e4c5 Avatar answered Oct 06 '22 02:10

e4c5