PHP - Generate an 8 character hash from an integer

前端 未结 6 1150
青春惊慌失措
青春惊慌失措 2020-12-17 00:05

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

相关标签:
6条回答
  • 2020-12-17 00:20

    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

    0 讨论(0)
  • 2020-12-17 00:33

    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);
    
    0 讨论(0)
  • 2020-12-17 00:37
    >>> 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))
    
    0 讨论(0)
  • 2020-12-17 00:37

    there are many ways ...

    one example

    $x = ?
    $s = '';
    for ($i=0;$i<8;++$i)
    {
        $s .= chr( $x%26 + ord('a') );
        $x /= 26;
    }
    
    0 讨论(0)
  • 2020-12-17 00:39
    $hash = substr(hash("sha256",$num), 0, 8);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题