Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute SHA1 of Strings in python

Tags:

python

hash

sha

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?

like image 575
kidd0 Avatar asked Sep 18 '14 01:09

kidd0


People also ask

How do you make a SHA1 hash in Python?

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.

What does Hashlib do in Python?

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

What is Hexdigest Python?

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.


1 Answers

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")
like image 134
Thomas Orozco Avatar answered Sep 20 '22 00:09

Thomas Orozco