Giving garbage value when trying to save md5 hash to file in python
m=md5.new()
a=10111011
>>> m.update(str(a))
>>> k=m.digest()
>>> k
'\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M'
>>> f.write(str(k))
>>> f.flush()
file f is filled with garbage value which I cannot use to re-read for further hash use. Why does this give a garbage value when, in python terminal, it gives correct output? And the worst part is the file is corrupted.
a source to share
If you need further clues as to where your garbage (your digest!) Comes from, try print k
versus print repr(k)
!
You have your original byte string. I think you want to insert hexdigest instead? Either use k = m.hexdigest()
or k = repr(m.digest())
and write this to your file.
Basically, you can choose your view, choose what you write to your file. Which ones do you want to see?
>>> print k
1 Y 6 M
>>> print repr(k)
'\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M'
>>> print k.encode("hex")
ec9d31896508a1c259f6bf36fee4e24d
Proceed in the same way for f.write (..) as you would for printing. As you can see, in the original version you used 'k' ('str (k)' is the same as once 'k')
a source to share
One possibility is that you are running Windows and did not open the file in binary mode, i.e. in quality 'wb'
. We cannot tell since you are not showing us how you discovered f
.
Another possibility might be that you are on Python 3 (where str
unicode stands for), but I think that in this case you will see the presenter b
when you show k
(and there is not md5
in the Python 3 standard library).
Opening the file the right way, with Python 2.6.4 on Mac, I see the digest as
'\x82s\xf9\xa4\x83\x04\x87\xd0\xfdg\xee\xfa\x1f\x05B>'
both k
as well as the contents of the file. I don’t know why you, by the way, see something else. I am getting the same result with Python 2.4 and 2.5.
a source to share