Frank N
Frank N

Reputation: 10376

Bash: Compare a partial hash of a variable to a fixed string

I got an environment variable %foo.

And within a linux bash script I want to:

I am just too dumb to properly chain things, but roughly like this:

...
if [ 'a0' != ${ $foo | bcrypt | awk '$1:0:2'} ]
  echo "Warn: typo in password?"
fi

Essentially it's meant as a smoke test (with comparing to the full hash being too much disclosure). (I do know, revelation still lowers security / eases brute-forcing around 30² or 250²-fold or so)

Upvotes: 0

Views: 130

Answers (1)

dash-o
dash-o

Reputation: 14424

You need to add "echo -n" to start of the pipe, and use substr in awk. Note '-n' is needed, otherwise the hash will include a trailing new line.

if [[ 'a0' != $( printf "%s" "$foo" | md5sum | awk '{ print substr($0, 0, 2) }' ) ]] ; then
  echo "Warn: typo in password?"
fi

Alternative, use bash instead of awk, and using 'here-string', you can write

hh=$(md5sum <<< "$foo")
if [[ 'a0' != ${hh:0:2} ]] ; then
  echo "Warn: typo in password?"
fi

Based on Kamil's suggestion for printf, possible to keep all logic inside the if, without the intermediate variable.

if [[ 'a0' != $(printf '%.2s' "$(md5sum <<< "$foo")") ]] ; then
  echo "Warn: typo in password?"
fi

Upvotes: 3

Related Questions