-1

an annoying question today, i should know this but for the life of me i can't figure it out. I am trying to hash a password before querying the sql database. I have the hash code working fine however its inside a public static string:

     public static string GetCrypt(string text)
    {
        string hash = "";
        SHA512 alg = SHA512.Create();
        byte[] result = alg.ComputeHash(Encoding.UTF8.GetBytes(text));
        hash = Encoding.UTF8.GetString(result);
        return hash;
    }

I have two questions, one.. once it is hashed, how do i go about getting that result as when i try to access the variable "hash" it gives the error does not exist in current context. I suspect this is due to public and private classes?

Also, my other question, to have a more effective program, can i or is this already, a code where by i type it once, then can call it passing variables back and forth. sort of like, enter a password, it hashes, then passes it back.. then in another textbox pass new variable to the same hash code and get new hashed variable back?

Thanks in advance guys!

Nicholas Mordecai
  • 859
  • 2
  • 12
  • 33

1 Answers1

5

To use this method you would store the return value, like this:

string hashedString = GetCrypt(inputString);

Then use hashedString as appropriate.

However, you have some problems:

  • The result of alg.ComputeHash() is not a UTF-8 encoded string, so Encoding.UTF8.GetString() is very likely to throw an exception, and won't even do what you want. Consider using Convert.ToBase64String() (or convert the byte array to a hex string).
  • You don't salt the input string, at least not within this method. This means your database of passwords is vulnerable to rainbow table attacks. Consider using salted hashes or (better yet) an algorithm design specifically for hashing passwords, such as bcrypt, scrypt, or PBKDF2 which is built in to the framework itself.
Community
  • 1
  • 1
cdhowie
  • 158,093
  • 24
  • 286
  • 300