简体   繁体   English

如何检查字符串是否是PHP中的有效sha256哈希?

[英]How to check if string is a valid sha256 hash in PHP?

How do I manage to identify a sha256 hash using PHP? 如何使用PHP识别sha256哈希? Also, is there any way to identify if the string is a sha256 hash even if it was salted? 另外,有没有办法确定字符串是否是sha256哈希,即使它是盐渍的?

I don't need to know the real value of the hash (I know that is impossible), but I need only to validate the string, so I can work in a way if the string is a sha256 hash and work another way if it isn't. 我不需要知道哈希的真正价值(我知道这是不可能的),但我只需要验证字符串,所以如果字符串是sha256哈希,我可以以某种方式工作,如果它是另一种方式不是。

The only way to check if a hash is a valid SHA-256 hash is to check 256 bits in it- if it does, then yes some input CAN possibly generate that output. 检查散列是否是有效SHA-256散列的唯一方法是检查其中的256位 - 如果是,则是某些输入CAN可能生成该输出。

Hashes are one way meaning I can give you a hash and you can never decrypt it (this is the difference between hashing and an encryption). 哈希是一种方式,这意味着我可以给你一个哈希,你永远不能解密它(这是哈希和加密之间的区别)。 This is good for storing passwords and such where the plain text value is irrelevant. 这适用于存储密码,以及纯文本值无关的情况。

I do not understand what you mean when you say: "even if it was salted". 当你说:“即使它被腌制”时,我也不明白你的意思。 Salting happens before hashing, it offers some protection against rainbow table attacks and users using the same password on multiple sites. Salting在散列之前发生,它提供了一些防止彩虹表攻击和在多个站点上使用相同密码的用户。 Depending on the base a simple regex can tell you if a particular string is a sha256 hash. 根据基础,简单的正则表达式可以告诉您特定字符串是否为sha256哈希。 i think most times we encounter hashes in base16, in that case this would work: 我想大多数时候我们在base16中遇到哈希,在这种情况下这会起作用:

   if (preg_match("/^([a-f0-9]{64})$/", $hash) == 1) {
      return true;
   } else {
      return false;
   }

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

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