简体   繁体   中英

Compute SHA1 of Strings in python

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?

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM