c# - 反转字符串哈希函数
问题描述
我有以下散列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
结果未知)?
解决方案
由于您不使用加密哈希,因此您的实现很容易反转(即返回一些 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
我们生成 astring
并hash
从中计算以进行检查)
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"
)
推荐阅读
- javascript - 使用 object.create 创建对象时创建默认参数
- swift - 对两个独立但半关联的视图模型的视图之间的特定状态变化进行通信/做出反应
- java - 无法正确替换 XWPFRun 文本
- c - 如何停止 inotify 结果的重复?
- php - 以 INR 方法格式化价格
- python - engine.runandWait() 卡住
- javascript - 使用 Next js 实现实时搜索
- python - 如何处理需要太多参数的函数?
- python - 从 FARM TextClassification 中提取概率和标签
- powershell - 如何使用 UTF-8 编码运行 ps1 脚本(从 Web 下载脚本)