Reversible hash function?

前端 未结 5 1420
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 01:41

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

5条回答
  •  感动是毒
    2020-11-30 02:31

    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. It's simple, it's fast, and it doesn't require knowing anything about boolean maths or crypo algorithms or anything else that requires actual thinking.

    The simplest would probably be to just move half the bits left, and the other half right:

    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 non-security uid).

    Also have a look at the multiplicative inverse answer given by Andy Hayden, below.

提交回复
热议问题