开发者

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

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]?


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


Try this for 32 characters:

if [[ $SOME_MD5 =~ ^[a-f0-9]{32}$ ]]
then
    echo "Match"
else
    echo "No match"
fi


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 ~ ]$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜