Rewriting Python SHA1 Digest code to Bash

60 Views Asked by At

On Debian machines I run the following Python code:

#!/usr/bin/env python3

text_in = "abcd".encode('utf8')

sha1 = hashlib.sha1()
sha1.update(text_in)
raw_digest = sha1.digest()
text_out = base64.b64encode(raw_digest)

print( "text_in: " + str(text_in) )
print( "text_out: " + str(text_out) )

Below is the result of Python code:

text_in: abcd
text_out: gf6L/odXbD7LIkJvjleEc4KRes8=

It's TRUE.

I'm trying to rewrite this Python code to Bash code:

#!/bin/sh

TEXT_IN="abcd"

DIGEST=$( echo -n "$TEXT_IN" | sha1sum | awk '{print $1}' )
TEXT_OUT=$( echo -n "$DIGEST" | base64 )

echo "TEXT_IN: $TEXT_IN"
echo "TEXT_OUT: $TEXT_OUT"

Below is the result of my Bash code:

TEXT_IN: abcd
TEXT_OUT: ODFmZThiZmU4NzU3NmMzZWNiMjI0MjZmOGU1Nzg0NzM4MjkxN2FjZg==

It's FALSE.

I need to run this Bash code in OpenWRT which is low on disk space and uses easy code in scripts, lightweight software and simple solutions.

Please help me rewrite this code from Python to Bash.

1

There are 1 best solutions below

1
pjh On

Try this Shellcheck-clean (except for a spurious warning about using a variable in the printf format string) Bash code:

#!/bin/bash -p

text_in='abcd'

printf_fmt=$(printf '%s' "$text_in" | sha1sum  \
                | sed -e 's/[[:space:]].*$//' -e 's/../\\x&/g')
text_out=$(printf "$printf_fmt" | base64)

printf 'text_in: %s\n' "$text_in"
printf 'text_out: %s\n' "$text_out"