测试字符串在PHP中是否为sha1 [英] Testing if string is sha1 in PHP
问题描述
我正计划将密码存储为sha1,因此我需要一种方法来验证它是否在我的网站的另一点.我打算使用preg_match,但不知道如何制作正则表达式模式.有人可以帮我一个忙吗?
I'm planning on storing the passwords as a sha1, so I need a way to validate that it is a sha1 at another point in my website. I was planning on using preg_match, but I do not know how to make regex patterns. Could someone help me out with one?
谢谢
我不是要看两个哈希是否匹配.
I am not trying to see if two hashes match.
推荐答案
实际上,您可以使用 preg_match()
确保它是一个40个字符的十六进制字符串,如下所示:
Actually, you can use preg_match()
to make sure it's a 40 characters hexadecimal string as such:
function is_sha1($str) {
return (bool) preg_match('/^[0-9a-f]{40}$/i', $str);
}
解释模式:
/ Opening Delimiter
^ Start Of String Anchor
[0-9a-f] Any of the following characters: 0123456789abcdef
{40} Repeated 40 times
$ End Of String Anchor
/ Closing Delimiter
i Modifier: Case-Insensitive Search
/ Opening Delimiter
^ Start Of String Anchor
[0-9a-f] Any of the following characters: 0123456789abcdef
{40} Repeated 40 times
$ End Of String Anchor
/ Closing Delimiter
i Modifier: Case-Insensitive Search
如果您要确保 sha1()
哈希与用户提供者的密码匹配,您只需像这样重新哈希:
If you are trying to make sure that the sha1()
hash matches the password the user provider, you simply rehash like this:
if($db_hash == sha1($user_provided_pass))
echo "Password is correct!";
这篇关于测试字符串在PHP中是否为sha1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!