Ben
Ben

Reputation: 305

Generating a sha256 from bash (without echo)

I am trying to write a basic script that runs through a file line by line, encrypts each line with sha256 and then compares it against a fixed test for matching results.

file.txt

foo
bar
bazz
password

my code:

#!/bin/bash
file="./file.txt"
while IFS='' read -r line || [[ -n "$line" ]] ; do
    password="5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
    echo "Testing $line: "
    try=$line | sha256sum
    if [[ "$try" == "$password" ]] ; then
        echo "match"
    else
        echo "no match"
    fi
done <"$file"

result:

testing foo
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  -
no match
testing bar
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  -
no match
testing bazz
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  -
no match
testing password
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  -
no match

I believe the try=$line | sha256sum to be the issue here because if I run it by itself using an example from the file.txt:

foo | sha256sum
foo: command not found
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  -

Placing foo in "" doesn't alter the result above

The only way I was able to get it to correctly handle the pipe was to place a echo in front:

echo -n foo | sha256sum
2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae

This isn't the desired results as I don't want to print each sha256sum I just want to encode the line and then check it. If it matches then print match, else no match.

Expected results:

testing foo #2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae  -
no match
testing bar #fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9  -
no match
testing bazz #ef9b462f01f881c97791114d6244476bb33e418d3dbe0ee0967c4c80e764cd9c  -
no match
testing password #5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8  -
match

Upvotes: 4

Views: 3895

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14520

printing the line in order to pipe it to sha256 won't print it to the screen. However, if you want to capture the output of sha256 you'll want to use a command substitution instead of just running the command.

That line should be:

try="$(printf '%s' "$line" | sha256sum | cut -f1 -d' ')"

We'll use printf instead of echo and then we capture stdout from the pipeline and store that in our variable try. Also, sha256sum prints the file from which it was reading, including stdin, so we'll use cut to get rid of that part.

Upvotes: 5

Related Questions