可逆的哈希函数? [英] Reversible hash function?

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

问题描述

我需要一个可逆的散列函数(很明显,输入的尺寸要比输出的小得多),它以随机的方式将输入映射到输出。基本上,我想要一种方法来将诸如123的数字转换为像9874362483910978这样的较大数字,但不是以保留比较的方式,所以它不一定总是如此,如果x1> x2,f(x1 )> f(x2)(但都不一定总是false)。

这个用例是我需要找到一种方法来将小数转换成更大,随机的。它们实际上并不需要是随机的(事实上,它们需要是确定性的,所以相同的输入总是映射到相同的输出),但它们需要随机查看(至少在base64编码时转换为字符串,所以移位Z位将不起作用,因为相似的数字将具有相似的MSB)。

另外,简单(快速)计算和反转是一个加号,但不是必需的。



我不知道我是否清楚,或者是否存在这样的算法,但我会很感激所有帮助!

解决方案

在给定问题的情况下,所提供的答案都不是特别有用。我有同样的问题,需要一个简单的,可逆的散列用于不安全的目的,并决定进行位重定位。最简单的可能是:

  def hash(n):
return((0x0000FFFF& n)< < 16)+((0xFFFF0000& n)>> 16)

,在该散列(hash(n))= n中,并且具有非序列对{n,m},n < m,其中hash(m)< hash(n)。

为了得到一个不太顺序的实现,你可能还想考虑从[msb,z,...,a,lsb ]到[msb,lsb,z,a,...]或[lsb,msb,a,z,...]或您感觉到的任何其他重定位都会为您处理的数字提供适当的非连续序列。 / p>

(上述函数对于适合32位的数字是安全的,大数字保证会导致冲突,并且需要更多的位掩码覆盖以防止出现问题。对于任何uid,32位通常就足够了)。

I need a reversible hash function (obviously the input will be much smaller in size than the output) that maps the input to the output in a random-looking way. Basically, I want a way to transform a number like "123" to a larger number like "9874362483910978", but not in a way that will preserve comparisons, so it must not be always true that, if x1 > x2, f(x1) > f(x2) (but neither must it be always false).

The use case for this is that I need to find a way to transform small numbers into larger, random-looking ones. They don't actually need to be random (in fact, they need to be deterministic, so the same input always maps to the same output), but they do need to look random (at least when base64encoded into strings, so shifting by Z bits won't work as similar numbers will have similar MSBs).

Also, easy (fast) calculation and reversal is a plus, but not required.

I don't know if I'm being clear, or if such an algorithm exists, but I'd appreciate any and all help!

解决方案

None of the answers provided seemed particularly useful, given the question. I had the same problem, needing a simple, reversible hash for not-security purposes, and decided to go with bit relocation. The simplest would probably be:

def hash(n):
  return ((0x0000FFFF & n)<<16) + ((0xFFFF0000 & n)>>16)

This is reversible, in that hash(hash(n)) = n, and has non-sequential pairs {n,m}, n < m, where hash(m) < hash(n).

To get a less sequential looking implementation, you might also want to consider an interlace reordering from [msb,z,...,a,lsb] to [msb,lsb,z,a,...] or [lsb,msb,a,z,...] or any other relocation you feel gives an appropriately non-sequential sequence for the numbers you deal with.

(The above function is safe for numbers that fit in 32 bits, larger numbers are guaranteed to cause collisions and would need some more bit mask coverage to prevent problems. That said, 32 bits is usually enough for any uid).

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

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