我有一个脚本来转换为基数62 (A-Za-z0-9),但是我如何从MD5中获得一个数字?
我在很多地方读到过,因为来自MD5的数字大于php可以处理的整数,所以它将是不准确的……因为我想要一个简短的URL,而且不打算使用整个散列,可能只有8个字符……
因此,我的问题是如何获得MD5散列的一部分编号?
而且,只使用MD5散列的一部分是不是一个坏主意?
发布于 2009-12-10 19:00:43
我将在这里提出一个不同的建议..既然您只对使用md5散列的十进制块感兴趣,为什么不使用CRC32或Adler等其他简短的数字散列呢?下面是一个示例:
$hash = sprintf('%u', crc32('your string here'));这将产生一个8位数的字符串哈希。
.:我想我误解了你,
GMP编辑(再次):要处理任意长度的数字,必须使用bc_math或扩展名here is a function that uses the bc_math extension and can also convert from base 2 up to base 62。你应该这样使用它:
echo bc_base_convert(md5('your url here'), 16, 62); // public base 62 hash反之亦然:
echo bc_base_convert('base 62 encoded value here', 62, 16); // private md5 hash希望能有所帮助。=)
发布于 2009-12-10 19:19:31
如果可能的话,我建议不要对你的URL使用散列。最终你会遇到碰撞。尤其是在截断散列的情况下。如果您继续实现一个基于ID的系统,其中每个项目都有一个惟一的ID,那么麻烦就会少得多。第一项将是1,第二项将是2,依此类推-如果您使用的是MySQL,只需抛出一个自动增量列。
创建短id的:
//the basic example
$sid = base_convert($id, 10, 36);
//if you're going to be needing 64 bit numbers converted
//on a 32 bit machine, use this instead
$sid = gmp_strval(gmp_init($id, 10), 36);将短id返回到基数10 id的:
//the basic example
$id = base_convert($id, 36, 10);
//if you're going to be needing 64 bit numbers
//on a 32 bit machine, use this instead
$id = gmp_strval(gmp_init($shortid, 36));希望这能有所帮助!
如果你真的想要基数62 (这不能用gmp或base_convert实现),看看这个:http://snipplr.com/view/22246/base62-encode--decode/
发布于 2009-12-10 19:05:45
你可以这样做:(并不是所有的步骤都是用php实现的,我已经用了很长时间了。)
$hash =md5(脚本,将该数字raw_output=true);
请参阅有关将字符串base conversion of arbitrary sized numbers in PHP
只使用md5的一小部分是没有风险的。所有的变化都是碰撞的危险。
https://stackoverflow.com/questions/1880169
复制相似问题