-2

I was looking to convert some old code I found to a .net standard compliant version. However I haven't used code like this before so I'm a bit lost on how to use it as it doesn't compile.

I understand that uint cannot be negative but how did this code work in the past?

public static uint Hash(string str, HashType hashType)
    {
        unsafe
        {
            uint cryptTable = 2146271213;
            uint num = -286331154;
            string upperInvariant = str.ToUpperInvariant();
            for (int i = 0; i < upperInvariant.get_Length(); i++)
            {
                uint num1 = (byte)upperInvariant[i];
                cryptTable = Crypto.CryptTable[&((uint)hashType * 256 + num1)] ^ cryptTable + num;
                num = num1 + cryptTable + num + (num << 5) + 3;
            }
            return cryptTable;
        }
    }

public enum HashType : uint
{
    FileHashTableIndex,
    FilePathA,
    FilePathB,
    TableKey
}
Scath
  • 3,777
  • 10
  • 29
  • 40
danewfie
  • 13
  • 3
  • 3
    Are you sure the code is the old one? Maybe instead of `unsafe` it had `unchecked`? – Gusman Jan 10 '18 at 18:16
  • @Gusman - No, it would have to be `unsafe` for the cryptTable assignment in the middle of the loop. Regarding it not compiling..that may just be that you have not allowed unsafe code in the project settings? Regarding the num assignment, `uint num = 0xEEEEEEEE;` is equivalent – zzxyz Jan 10 '18 at 18:22
  • @zzxyz 0xEEEEEEEE allowed it to compile. Until I convert the code fully I won't know if this works or not. just running a console app returns a position value, could you explain the conversion to me or how I can figure this out in the future? – danewfie Jan 10 '18 at 18:33
  • The code you have doesn't even build – Joe Phillips Jan 10 '18 at 18:35
  • Sure, just punch the number into `calc` in programmer mode on Windows. Make sure it's set to decimal and DWORD (for a 4-byte value), and it'll show you the hex equivalent. Linux has various calculators that will do the same thing. As will various debuggers. – zzxyz Jan 10 '18 at 18:37
  • I'm not sure about the value of porting this code, by the way. This looks like an amateur attempt to obfuscate the hash. I would either use a .NET builtin: `str.ToUpperInvariant().GetHashCode()` or one of the hash methods in the cryptography libraries, like a SHA1 hash or something newer. Disclaimer: I am FAR from a cryptography expert, but I wouldn't trust this code as far as I could throw it unless I had independent proof of its value. – zzxyz Jan 10 '18 at 18:50
  • 1
    Anyway, if you surround the code with `unchecked{ }` the code will work. – Gusman Jan 10 '18 at 19:12

1 Answers1

0

Converting the uint to: uint num = 0xEEEEEEEE;

This fixed the problem. Thanks to @zzxyz for the tip and howto!

danewfie
  • 13
  • 3