7

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!

T. Zengerink
  • 4,189
  • 5
  • 29
  • 31
doc
  • 105
  • 1
  • 1
  • 7
  • With `base_convert`, you could go down to a maximum of 3 characters (!) for your range of numbers. If you always need 8, you probably want [`(new Id())->encode($id)`](https://github.com/delight-im/PHP-IDs). You may have to prepend leading zeros (or other characters), but even substrings of MD5 can have leading zeros (though with lower probability). – caw Nov 20 '19 at 15:10

6 Answers6

23

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);
nickf
  • 520,029
  • 197
  • 633
  • 717
Nathan Osman
  • 67,908
  • 69
  • 250
  • 347
4
>>> 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))
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
1

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

Ariel
  • 11
  • 1
0

there are many ways ...

one example

$x = ?
$s = '';
for ($i=0;$i<8;++$i)
{
    $s .= chr( $x%26 + ord('a') );
    $x /= 26;
}
SteelBytes
  • 6,806
  • 1
  • 25
  • 28
  • isn't this just effectively changing the base of the number? – nickf Mar 26 '10 at 02:25
  • sure. but the request was pretty vague - it just asked for an 8char hash. – SteelBytes Mar 26 '10 at 02:26
  • Sorry about how vaguely I asked the question :( I'm trying to generate an 8 character hash from any integer but don't just want to pad the remaining length of the hash with something. Any ideas? – doc Mar 26 '10 at 02:34
0
$hash = substr(hash("sha256",$num), 0, 8);
ghostdog74
  • 307,646
  • 55
  • 250
  • 337
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.

symcbean
  • 46,644
  • 6
  • 56
  • 89