Skip to main content
 首页 » 编程设计

c#之如何评估这两个哈希函数

2024年02月13日12java哥

代码1:(将SHA1结果转换为字符串的简单方法)

byte[] bs = System.Text.Encoding.UTF8.GetBytes(input); 
SHA1CryptoServicesProvider x = new SHA1CryptoServicesProvider(); 
bs = x.ComputeHash(bs); 
System.Text.StringBuilder s = new System.Text.StringBuilder(); 
foreach (byte b in bs) 
   s.Append(b.ToString("x2").ToLower()); 
result1 = s.ToString(); 

Code2:(世界一开始就存在于项目中的遗留代码)

byte[] bs = System.Text.ASCIIEncoding.GetBytes(input); 
SHA1CryptoServicesProvider x = new SHA1CryptoServicesProvider(); 
bs = x.ComputeHash(bs); 
char[] c = new char[bs.length] 
for(int i=0; i<bs.length; i++) 
  c[i] = (char)(bs[i] & 0x7f); 
resutl2 = new StringBuilder().Append(c).ToString(); 

有没有map()函数可以用result2计算result1?

result1 == map(result2) 

0x7f 中的“代码 2”是什么意思?

请您参考如下方法:

And what does the "Code 2" mean by 0x7f?

& 0x7f 表示 & 128,即“仅保留前(最低有效)7 位”,这会强制输出保持纯 ASCII(ASCII 仅使用7 位)- 通过简单地丢弃任何不适合的信息。

Is there any map() function to evaluate result1 with result2?

不过,最大的问题是在开始时使用了不同的编码:除非 input 只包含 ASCII 文本(即只使用前 7 位的字符),否则你的哈希值完全不同字节数组 (bs),因此最终输出不会以任何方式相等。由于哈希不是简单可逆的,因此您将无法对此进行补偿。