生成较短的公共ID [英] Generate shorter public id

查看:182
本文介绍了生成较短的公共ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来为我的对象生成公共id(例如facebook uid)。该id应该是唯一的,用户不应该猜测它(或下一个)。



现在我正在使用这个:

  sha1('fixed a fixed string'。$ this-> getId())

问题是sha1会生成很长的字符串(40个字符),我希望它更短。我想过使用MD5,但它已知不会保存,因为您可以创建冲突。这是真的在我的情况是一个问题吗?



我有什么替代方案?

解决方案我做了一些测试,看看id将使用不同的哈希函数多久。我还用 convBase 将0-9a -z到0-9a-zA-Z,建议使用

  $ i = mt_rand(1,PHP_INT_MAX); 
sha1($ i):40 322c73c44958e4219fd6679aead094192cb672fe
convBase(sha1($ i)):34 1JHrlXObHSVMcbn2bHRBCBIRD3RVKQHMQzg
md5($ i):32 7b09f8cd76be44403b90e971a5a61e6c
convBase(md5($ i) ):28 5bgdGpBZekbb3PQlILrSKMtHC24A
$ i:9 107300785
convBase($ i):5 7gdPP

因此,即使转换为其他基数,sha1也是非常长的。另外我还不确定MD5是否安全。无论如何,有28个字符,如果你想在twitter上发布它,它仍然很长:
http://mydomainsux.com/invite/5bgdGpBZekbb3PQlILrSKMtHC24A



使用 convBase($ i)存在不唯一的问题。你将不得不手动检查。不过,我认为这是要走到这里的方法,因为如果你使用散列,那么也可能会有一个自然的勾结,所以你必须检查。



我读到你可以预先在表格中生成ID,并在需要时选择一个。这样你不必每次都测试唯一性。


I am looking for a way to generate public ids for my objects (like a facebook uid). The id should be unique and the user should not be able to guess it (or the next one).

Right now I am using this:

sha1('a fixed random string' . $this->getId())

The problem is that sha1 generates very long strings (40 chars) and I would like it to be shorter. I thought about using MD5 but it's known to be not save because you can create collisions. Is this really a problem in my case?

What alternatives do I have?

解决方案

I made some tests to see how long the id will be using different hash functions. I also used convBase to convert from 0-9a-z to 0-9a-zA-Z as suggested:

$i = mt_rand(1, PHP_INT_MAX);
sha1($i):           40 322c73c44958e4219fd6679aead094192cb672fe
convBase(sha1($i)): 34 1JHrlXObHSVMcbn2bHRBCBIRD3RVKQHMQzg
md5($i):            32 7b09f8cd76be44403b90e971a5a61e6c
convBase(md5($i)):  28 5bgdGpBZekbb3PQlILrSKMtHC24A
$i:                  9 107300785
convBase($i):        5 7gdPP

So sha1 is very long even if converted to the other base. Also I am still not sure if MD5 is secure. Anyway, with 28 characters it is still kind of long if you want to post it in an URL on twitter: http://mydomainsux.com/invite/5bgdGpBZekbb3PQlILrSKMtHC24A

The shortest solution with convBase($i) has the problem of not being unique. You would have to check for that manually. Still, I think this is the way to go here because if you use a hash there could also be a natural collusion so you have to check anyway.

I read that you can pre generate the id's in a table and just pick one whenever you need one. This way you do not have to test for uniqueness every time.

这篇关于生成较短的公共ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆