一对一整数映射函数 [英] One-to-one integer mapping function

查看:375
本文介绍了一对一整数映射函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用MySQL并开发一个应用程序,我们希望ID序列不会公开显示... ID不是绝对秘密,如果有人能够解码它们没有重大问题。 p>

所以,哈希当然是明显的解决方案,我们目前使用MD5 ... 32位整数进入,我们将MD5修剪为64位,然后存储。然而,我们不知道当你修剪这样(特别是因为所有的数字来自autoincrement或当前时间)碰撞有多大可能。我们目前检查冲突,但由于我们可能一次插入100.000行性能是可怕的(不能批量插入)。



但最终,我们真的不需要由哈希提供的安全,他们消耗不必要的空间,还需要一个额外的索引...所以,有任何简单和足够好的功能/算法,以保证任何数字的一对一映射没有明显的视觉模式的序列号?



编辑:我使用的PHP不支持整数算术默认情况下,但是环顾我发现它可以便宜地复制与按位运算符。可在此处找到32位整数乘法的代码: http://pastebin.com/np28xhQF



或者乘以一个奇数mod 2 ^

如果这样做的话,你可以简单地与0xDEADBEEF进行XOR。 32。对于逆映射,只需乘以乘法逆



示例:n = 2345678901;乘法逆(mod 2 ^ 32):2313902621
对于映射只乘以2345678901(mod 2 ^ 32):



1 - > 2345678901
2 - > 396390506



对于逆映射,乘以2313902621。


We are using MySQL and developing an application where we'd like the ID sequence not to be publicly visible... the IDs are hardly top secret and there is no significant issue if someone indeed was able to decode them.

So, a hash is of course the obvious solution, we are currently using MD5... 32bit integers go in, and we trim the MD5 to 64bits and then store that. However, we have no idea how likely collisions are when you trim like this (especially since all numbers come from autoincrement or the current time). We currently check for collisions, but since we may be inserting 100.000 rows at once the performance is terrible (can't bulk insert).

But in the end, we really don't need the security offered by the hashes and they consume unnecessary space and also require an additional index... so, is there any simple and good enough function/algorithm out there that guarantees one-to-one mapping for any number without obvious visual patterns for sequential numbers?

EDIT: I'm using PHP which does not support integer arithmetic by default, but after looking around I found that it could be cheaply replicated with bitwise operators. Code for 32bit integer multiplication can be found here: http://pastebin.com/np28xhQF

解决方案

You could simply XOR with 0xDEADBEEF, if that's good enough.

Alternatively multiply by an odd number mod 2^32. For the inverse mapping just multiply by the multiplicative inverse

Example: n = 2345678901; multiplicative inverse (mod 2^32): 2313902621 For the mapping just multiply by 2345678901 (mod 2^32):

1 --> 2345678901 2 --> 396390506

For the inverse mapping, multiply by 2313902621.

这篇关于一对一整数映射函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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