BASH:有一种简单的方法来检查字符串是否是有效的SHA-1(或MD5)哈希?

时间:2011-10-05 13:57:36

标签: regex bash

这一切都在标题中。

解决问题的另一种方法是:在BASH中,检查字符串是[0-9][a-f]范围内的40(或32)个字符序列的简洁方法是什么?

3 个答案:

答案 0 :(得分:9)

尝试32个字符:

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

答案 1 :(得分:8)

有一个功能:

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

如果 shell 支持 POSIX字符类,则可以使用 [![:xdigit:]]代替[!0-9A-Fa-f]

答案 2 :(得分:1)

stringZ=0123456789ABCDEF0123456789ABCDEF01234567

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

然后,测试${#stringZ}是否等于expr "$stringZ" : '[0-9a-fA-F]\{32\}\|[0-9a-fA-F]\{40\}',如果字符串是32或40个字符且只有十六进制数字,则应该为真。

像这样:

#!/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

输出:

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