首页 > 解决方案 > 反转字符串哈希函数

问题描述

我有以下散列a的函数string

public static uint hashString(string myString)
{
     uint hash = 0;

     foreach (char c in myString)
     {
         hash *= 0x1F;
         hash += c;
     }

     return hash;
}

所以如果我想散列hello它会产生99162322.

是否可以编写一个反向函数来接收 anumber并吐出string(假设string 结果未知)?

标签: c#hashreverse

解决方案


由于您不使用加密哈希,因此您的实现很容易反转(即返回一些 string具有给定哈希值的内容)

代码:

public static uint hashString(string myString) {
  //DONE: validate public methods' parameters
  if (null == myString)
    return 0;

  uint hash = 0;

  //DONE: hash function must never throw exceptions
  unchecked {
    foreach (char c in myString) {
      hash *= 0x1F;
      hash += c;
    }
  }

  return hash;
}

private static string HashReverse(uint value) {
  StringBuilder sb = new StringBuilder();

  for (; value > 0; value /= 31) 
    sb.Append((char)(value % 31));

  return string.Concat(sb.ToString().Reverse());
}

演示:(给定 ahash我们生成 astringhash从中计算以进行检查)

uint[] tests = new uint[] {
  99162322,
  123,
  456
};

// Since the string can contain control characters, let's provide its Dump
string Dump(string value) => string.Join(" ", value.Select(c =>((int) c).ToString("x4")));

string report = string.Join(Environment.NewLine, tests
  .Select(test => new { 
    test,
    reversed = HashReverse(test)
  })
  .Select(item => $"{item.test,9} :: {Dump(item.reversed),-30} :: {hashString(item.reversed),9}"));

Console.WriteLine(report);

结果:

 99162322 :: 0003 000e 000b 0012 0012 0012  ::  99162322
      123 :: 0003 001e                      ::       123
      456 :: 000e 0016                      ::       456

请注意,许多astring产生相同的哈希值(例如,"hello"和我的"\u0003\u000e\u000b\u0012\u0012\u0012"


推荐阅读