.NET Framework 4.5 and later can be configured to use a randomized string hashing algorithm. How can a managed-code library check whether the framework is using such an algorithm?
A library of ours has a legacy feature that unfortunately depends on String.GetHashCode returning the same hash codes even on different machines. The legacy feature is now disabled by default. If an application attempts to enable the legacy feature in an application domain where String.GetHashCode uses a randomized algorithm, I'd like the library to throw an exception saying that the legacy feature is not supported in that configuration.
I can think of these solutions:- Call "test".GetHashCode() and check that the result is 0xEAE38E77 in a 32-bit process or 0xCC127386 in a 64-bit process. There is a small risk that the result matches even if randomized hashing is enabled, but it is extremely likely that a mismatch would be found during testing of the application.
- Check for the UseRandomizedStringHashAlgorithm element in the application configuration file. This seems a bad solution because there are at least four other ways to enable randomized string hashing: environment variable, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, and AppDomainSetup.SetCompatibilitySwitches.
- Call the private method String.UseRandomizedHashing() by reflection. Nobody guarantees it will still be there in future versions of the .NET Framework.
I'm leaning towards the first solution. Do you have better ideas?