Dear Readers,
The last time I have spent on the development of SKGL API, which is a library for those of you who want to secure, protect your hard-coded .NET application. I meanwhile, I have also spent sometime on a code, (basically half an hour), that produces hash code. It is not the best way of doing it, however, so it would be a pleasure to see another version of this code. Much appreciated!
static string twentyfiveByteHash (string s)
{
int amountOfBlocks = s.Length / 5;
string[] preHash = new string[amountOfBlocks];
if (s.Length <= 5)
{
//if the input string is shorter than 5, no need of blocks!
preHash[0] = GetStableHash(s).ToString ();
}
else if (s.Length > 5)
{
//if the input is more than 5, there is a need of dividing it into blocks.
for (int i = 0; i < amountOfBlocks-1; i++)
{
preHash[i] = GetStableHash (s.Substring(i*5,5)).ToString ();
}
preHash[preHash.Length-1] = GetStableHash (s.Substring((preHash.Length-1) * 5, s.Length - (preHash.Length - 1) * 5)).ToString ();
}
return String.Join ("",preHash);
}
static public int GetStableHash(string s)
{
/*
* modification of code from:
* http://stackoverflow.com/questions/548158/fixed-length-numeric-hash-code-from-variable-length-string-in-c-sharp
*
* modified by Artem Los
*
*/
const int MUST_BE_LESS_OR_EQUAL_TO = 100000000;
uint hash = 0;
foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))
{
hash += b;
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
int result = (int)(hash % MUST_BE_LESS_OR_EQUAL_TO);
int check = MUST_BE_LESS_OR_EQUAL_TO / result;
if (check > 1)
{
result *= check;
}
return result;
}