Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce MD5 - Using a different base

Tags:

php

hash

radix

My client generates promotional coupon codes which are nothing but 32 char MD5 hashes.

My job is to reduce the MD5 string from 32 chars to less than 10 chars in a way that the hash can be recreated from the reduced string.

The reduction is important as it would be easier for users to reproduce the reduced hash.

For e.g.: 719bedacf2e560b27f39d80accc67ffd => ZjKa1Gh (not mathematically true)

I came across this: How to reduce hash value's length?

It suggests: Using a different base

I am clueless as to how to do this in PHP, can we decode a string to its ASCII and re-encode it?

Are there any in-built functions in PHP that I can use in this case?

Update using https://packagist.org/packages/aza/math

$original = '719bedacf2e560b27f39d80accc67ffd';
$long1 = NumeralSystem::convert($original, 16, 10);
$short = NumeralSystem::convertTo($long1, 62);
$long2 = NumeralSystem::convertFrom($short, 62);
$recovered = NumeralSystem::convert($long2, 10, 16);

var_dump($long1);
var_dump($short);
var_dump($long2);
var_dump($recovered);

// output
string(39) "151012390170261082849236619706853916669"
string(22) "3SNOKWefotgnnCmWnYkTOf"
string(39) "151012390170261082849236619706853916669"
string(32) "719bedacf2e560b27f39d80accc67ffd"

Seems like the lowest I can reach from 32 chars MD5 is 22 chars this way. I am still looking for ways in which I can further reduce it to 10 chars.

Update: Using first half of MD5

$original = '719bedacf2e560b';
$coupon = NumeralSystem::convert($original, 16, 62);
$recovered = NumeralSystem::convert($coupon, 62, 16);

var_dump($coupon);
var_dump($recovered);

// output
string(10) "bnMR3RjZil"
string(15) "719bedacf2e560b"

If the user is providing bnMR3RjZil I can use that to recreate 719bedacf2e560b and then do a MySQL LIKE search to get the full MD5. If it returns a row I can then get forward with the promotional activity.

like image 522
Donnie Ashok Avatar asked Mar 28 '26 21:03

Donnie Ashok


1 Answers

My job is to reduce the MD5 string from 32 chars to less than 10 chars in a way that the hash can be recreated from the reduced string.

That isn't possible. A MD5 hash is 128 bits; an ASCII character is 7 bits. There's no way to store an MD5 hash in any less than 128÷7 = 18.2 (round up to 19) ASCII characters, and even that would include nonprintable control characters.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!