简体   繁体   English

测试PHP中字符串是否为sha1

[英]Testing if string is sha1 in PHP

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. 我打算将密码存储为sha1,所以我需要一种方法来验证它在我网站的另一个点是sha1。 I was planning on using preg_match, but I do not know how to make regex patterns. 我打算使用preg_match,但我不知道如何制作正则表达式模式。 Could someone help me out with one? 有人可以帮助我吗?

Thanks 谢谢

Edit: I am not trying to see if two hashes match. 编辑:我不是要看两个哈希是否匹配。

Actually, you can use preg_match() to make sure it's a 40 characters hexadecimal string as such: 实际上,你可以使用preg_match()来确保它是一个40个字符的十六进制字符串:

function is_sha1($str) {
    return (bool) preg_match('/^[0-9a-f]{40}$/i', $str);
}

To explain the pattern: 解释模式:

/ 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


If you are trying to make sure that the sha1() hash matches the password the user provider, you simply rehash like this: 如果您正在尝试确保sha1()哈希与用户提供程序的密码匹配,则只需重新进行如下操作:

if($db_hash == sha1($user_provided_pass))
   echo "Password is correct!";

ctype_xdigit is much faster. ctype_xdigit要快得多。 I typically use hashes for lookups and find it very useful. 我通常使用哈希进行查找,并发现它非常有用。

When comparing two SHA1 hashes, and you know that the first one is one (because it comes out of the database), then just assume that the second is a SHA1 value as well. 比较两个SHA1哈希,并且您知道第一个是哈希值(因为它来自数据库),那么假设第二个哈希值也是SHA1值。 You are only interested if two hashes match or not. 你只对两个哈希匹配与否感兴趣。 If one of the compared values is not a possible SHA1 value, then it's particulary not the same as the one in the database. 如果其中一个比较值不是可能的SHA1值,则它与数据库中的值不同。 And that's all you need to know. 这就是你需要知道的全部内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM