PHP - Generate an 8 character hash from an integer

你。 提交于 2019-11-27 18:19:53

问题


Is there a way to take any number, from say, 1 to 40000 and generate an 8 character hash?

I was thinking of using base_convert but couldn't figure out a way to force it to be an 8 character hash.

Any help would be appreciated!


回答1:


Why don't you just run md5 and take the first 8 characters?

Because you are wanting a hash, it doesn't matter whether portions are discarded, but rather that the same input will produce the same hash.

$hash = substr(md5($num), 0, 8);



回答2:


>>> math.exp(math.log(40000)/8)
3.7606030930863934

Therefore you need 4 digit-symbols to produce a 8-character hash from 40000:

sprintf("%08s", base_convert($n, 10, 4))



回答3:


For php:

$seed = 'JvKnrQWPsThuJteNQAuH';
$hash = sha1(uniqid($seed . mt_rand(), true));

# To get a shorter version of the hash, just use substr
$hash = substr($hash, 0, 10);

http://snipplr.com/view.php?codeview&id=20236




回答4:


there are many ways ...

one example

$x = ?
$s = '';
for ($i=0;$i<8;++$i)
{
    $s .= chr( $x%26 + ord('a') );
    $x /= 26;
}



回答5:


$hash = substr(hash("sha256",$num), 0, 8);



回答6:


So you want to convert a 6 digit number into a 8 digit string reproducibly?

sprintf("%08d", $number);

Certainly a hash is not reversible - but without a salt / IV it might be a bit easy to hack. A better solution might be:

substr(sha1($number . $some_secret),0,8);

C.



来源:https://stackoverflow.com/questions/2520794/php-generate-an-8-character-hash-from-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!