I have a file which contains a lot of Strings. I am trying to compute SHA1 hashes of these strings individually and store those
import hashlib
inp = open("inp.txt" , "r")
outputhash = open("outputhashes.txt", "w")
for eachpwd in inp:
sha_1 = hashlib.sha1()
sha_1.update(eachpwd)
outputhash.write(sha_1.hexdigest())
outputhash.write("\n")
The issue I am facing is once a strings SHA1 is computed the next string is being appended(I feel this is why I am not getting the correct hashes) and its hash is being computed. Hence I am not getting the correct hashes. I am new to python. I know what to do but don't know how to do it. Can you point me in the right direction to go about this?
Using update() In the earlier examples we have created the hash object initialized with the encoded string or byte string. There is another way to append the byte string to the sha1 hash object using update() method. You can use the update() multiple times to append the byte string or any other byte date.
This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 algorithm (defined in internet RFC 1321).
hexdigest() : the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.
You're iterating over a file, which is going to return the lines, including the line terminator (a \n
character at the end of the string)
You should remove it:
import hashlib
inp = open("inp.txt" , "r")
outputhash = open("outputhashes.txt", "w")
for line in inp: # Change this
eachpwd = line.strip() # Change this
# Add this to understand the problem:
print repr(line)
sha_1 = hashlib.sha1()
sha_1.update(eachpwd)
outputhash.write(sha_1.hexdigest())
outputhash.write("\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With