Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: Is there a simple way to check whether a string is a valid SHA-1 (or MD5) hash?

Tags:

regex

bash

It's all in the title.

An alternative way to phase the problem is: in BASH, what is a concise way of checking whether a string is a sequence of 40 (or 32) characters in the ranges [0-9] and [a-f]?

like image 950
Philippe Avatar asked Oct 05 '11 13:10

Philippe


3 Answers

With a function:

is_valid() {
    case $1 in
      ( *[!0-9A-Fa-f]* | "" ) return 1 ;;
      ( * )                
        case ${#1} in
          ( 32 | 40 ) return 0 ;;
          ( * )       return 1 ;;
        esac
    esac    
  }

If the shell supports POSIX character classes [![:xdigit:]] could be used instead of [!0-9A-Fa-f].

like image 106
Dimitre Radoulov Avatar answered Nov 16 '22 09:11

Dimitre Radoulov


Try this for 32 characters:

if [[ $SOME_MD5 =~ ^[a-f0-9]{32}$ ]]
then
    echo "Match"
else
    echo "No match"
fi
like image 34
aioobe Avatar answered Nov 16 '22 08:11

aioobe


stringZ=0123456789ABCDEF0123456789ABCDEF01234567

echo ${#stringZ}
40
echo `expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'`
40

Then, test if ${#stringZ} equals expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}' and it should be true if the string is 32 or 40 characters and only hexadecimal digits.

Like so:

#!/bin/bash
stringZ=""
while [ "$stringZ" != "q" ]; do
    echo "Enter a 32 or 40 digit hexadecimal ('q' to quit): "
    read stringZ
    if [ "$stringZ" != "q" ]; then
        if [ -n $stringZ ] && [ `expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}'` -eq ${#stringZ} ]; then
            echo "GOOD HASH"
        else
            echo "BAD HASH"
        fi
    fi
done

Output:

[ 07:45 jon@host ~ ]$ ./hexTest.sh 
Enter a 32 or 40 digit hexadecimal ('q' to quit):
1234567890abcdef1234567890abcdef
GOOD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
1234567890abcdef1234567890abcdef01234567
GOOD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
1234567890abcdef1234567890abcdef0
BAD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
123
BAD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
abcdef
BAD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
0123456789ABCDEF0123456789aBcDeF98765432
GOOD HASH
Enter a 32 or 40 digit hexadecimal ('q' to quit):
q
[ 07:46 jon@host ~ ]$
like image 1
chown Avatar answered Nov 16 '22 10:11

chown