PHP - 从一个整数生成一个 8 个字符的哈希

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2520794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:48:43  来源:igfitidea点击:

PHP - Generate an 8 character hash from an integer

phphashbase-conversion

提问by doc

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

有没有办法取任何数字,从 1 到 40000 并生成一个 8 个字符的哈希?

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

我正在考虑使用base_convert但无法想出一种方法将其强制为 8 个字符的哈希值。

Any help would be appreciated!

任何帮助,将不胜感激!

回答by Nathan Osman

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

你为什么不直接跑去md5取前 8 个字符呢?

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);

回答by Ignacio Vazquez-Abrams

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

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

因此,您需要 4 个数字符号才能从 40000 生成 8 个字符的散列:

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

回答by Ariel

For php:

对于 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

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

回答by symcbean

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

那么您想将 6 位数字可重复地转换为 8 位字符串吗?

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:

当然,散列是不可逆的——但如果没有盐/IV,它可能有点容易被破解。更好的解决方案可能是:

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

C.

C。

回答by SteelBytes

there are many ways ...

有很多方法...

one example

一个例子

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

回答by ghostdog74

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