在编码之前,我注意到有关SHA256的一些奇怪之处,因为它似乎比哈希的字母生成更多的整数。起初我以为我只是想象它,所以我做了一个快速测试以确保。令人惊讶的是,我的测试似乎证明SHA256支持它生成的哈希值中的整数值。我想知道为什么会这样。哈希索引是一个字母和一个数字之间的差异应该是完全相同的吗?这是我的测试示例:
namespace TestingApp
{
static class Program
{
private static string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static char[] characters = letters.ToCharArray();
private static Random _rng = new Random();
static void Main(string[] args)
{
int totalIntegers = 0;
int totalLetters = 0;
for (int testingIntervals = 0; testingIntervals < 3000; testingIntervals++)
{
string randomString = NextString(10);
string checksum = DreamforceChecksum.GenerateSHA256(randomString);
int integerCount = checksum.Count(Char.IsDigit);
int letterCount = checksum.Count(Char.IsLetter);
Console.WriteLine("String: " + randomString);
Console.WriteLine("Checksum: " + checksum);
Console.WriteLine("Integers: " + integerCount);
Console.WriteLine("Letters: " + letterCount);
totalIntegers += integerCount;
totalLetters += letterCount;
}
Console.WriteLine("Total Integers: " + totalIntegers);
Console.WriteLine("Total Letters: " + totalLetters);
Console.Read();
}
private static string NextString(int length)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++)
{
builder.Append(characters[_rng.Next(characters.Length)]);
}
return builder.ToString();
}
}
}
和我的校验和/哈希类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace DreamforceFramework.Framework.Cryptography
{
public static class DreamforceChecksum
{
private static readonly SHA256Managed _shaManagedInstance = new SHA256Managed();
private static readonly StringBuilder _checksumBuilder = new StringBuilder();
public static string GenerateSHA256(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] hash = _shaManagedInstance.ComputeHash(bytes);
_checksumBuilder.Clear();
for (int index = 0; index < hash.Length; index++)
{
_checksumBuilder.Append(hash[index].ToString("x2"));
}
return _checksumBuilder.ToString();
}
public static byte[] GenerateSHA256Bytes(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] hash = _shaManagedInstance.ComputeHash(bytes);
_checksumBuilder.Clear();
for (int index = 0; index < hash.Length; index++)
{
_checksumBuilder.Append(hash[index].ToString("x2"));
}
return Encoding.UTF8.GetBytes(_checksumBuilder.ToString());
}
public static bool ValidateDataIntegrity(string data, string targetHashcode)
{
return GenerateSHA256(data).Equals(targetHashcode);
}
}
}
我已多次运行我的测试,并且每次看起来哈希中生成的整数比字母更多。以下是3次测试:
有谁知道为什么SHA256似乎更喜欢数字而不是字母和数字的平均分配?
答案 0 :(得分:25)
鉴于可能有10位数和6位字母,比例应大致为10:6。这与您的结果一致。
答案 1 :(得分:2)
输出为十六进制。 0-9和a-f