從微軟的Reference Source兩者,一個實現是:
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
[System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override int GetHashCode() {
#if FEATURE_RANDOMIZED_STRING_HASHING
if(HashHelpers.s_UseRandomizedStringHashing)
{
return InternalMarvin32HashString(this, this.Length, 0);
}
#endif // FEATURE_RANDOMIZED_STRING_HASHING
unsafe {
fixed (char *src = this) {
Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Contract.Assert(((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
#if WIN32
int hash1 = (5381<<16) + 5381;
#else
int hash1 = 5381;
#endif
int hash2 = hash1;
#if WIN32
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27))^pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27))^pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27))^pint[0];
}
#else
int c;
char *s = src;
while ((c = s[0]) != 0) {
hash1 = ((hash1 << 5) + hash1)^c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2)^c;
s += 2;
}
#endif
#if DEBUG
// We want to ensure we can change our hash function daily.
// This is perfectly fine as long as you don't persist the
// value from GetHashCode to disk or count on String A
// hashing before string B. Those are bugs in your code.
hash1 ^= ThisAssembly.DailyBuildNumber;
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
這是不能跨越.NET版本穩定,從散落在string.cs源代碼註釋,甚至有可能不會是穩定整個應用程序域之內相同的過程。
如果您想要一個真正穩定的哈希代碼,可以「安全地」保存在AppDomain之外,請查看System.Security.Cryptography
中的哈希函數。 MD5
是低安全工作可接受的,SHAx
口味更好。
True Hashes只有一種方法,它不可能真正反轉散列,因爲它是一個「有損」的過程。如果開發人員從索賠中獲得代碼,他們可以反轉哈希,但他們要麼撒謊,弄錯或者沒有實施正確的哈希。
.NET中的哈希碼在各個版本中都不穩定。 [這是來自.net核心的一個實現](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs) –
跨版本的穩定性有關係嗎?它只是在程序運行時產生相同的值,不是? – Icepickle
從[源代碼](https://referencesource.microsoft.com/#mscorlib/system/string.cs)中的註釋,不僅在.net版本中不穩定,它在AppDomain之間甚至可能不穩定相同的過程。 –