从较长的字符串生成较短的哈希字符串的最佳方法是什么
我正在尝试从 Ruby 中的较长字符串创建较短的非冲突字符串。最好的方法是什么? Base64 编码 MD5 哈希值?
这是用例:
loop do
key = short_hash("#{user_id}-#{timestamp}")
break if $redis.setnx(key, "0")
end
我不希望密钥太长。
I'm trying to create short non-colliding strings from longer strings in Ruby. What's the best way to do this? Base64 encode a MD5 hash?
This is the use case:
loop do
key = short_hash("#{user_id}-#{timestamp}")
break if $redis.setnx(key, "0")
end
I don't want key to be too long.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我经常使用 SHA 来实现这一点,类似于您的示例。它不能保证是唯一的,但通常足以满足大多数用途:
ruby UUID gem 是另一种选择。
但在您的具体情况下,既然您使用的是 redis,为什么不只使用 redis INCR 命令呢?然后您至少可以保证数据库内的唯一性。例如:
I often use a SHA has for this similar to the example you have. It's not guaranteed to be unique, but is usually good enough for most purposes:
The ruby UUID gem is another option.
But in your specific case since you're using redis, why not just use the redis INCR command? Then you can guarantee the uniqueness at least within your database. For example:
您可以使用哈希函数创建不太可能发生冲突的较短字符串。然而,鸽巢原理保证你将能够找到两个较长的字符串将哈希为相同的值。
要生成真正唯一的值,您可能必须分配一个连续的标识号。但这还要求您跟踪与哪个输入字符串关联的标识号。
You can use a hash function to create shorter strings that aren't likely to collide. However, the Pigeonhole principle guarantees that you will be able to find two longer strings that will hash to the same value.
To generate truly unique values, you may have to assign a sequential identification number. But this would also require that you keep track of which identification number you have associated with which input string.