简体   繁体   中英

The right way to compare hashed passwords

I have a field in my database which is binary(32) for storing SHA-256 passwords. Since MSSQL store the hash in upper case and with 0x prefix, I've done this:

public static string getHashSha256(string text)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        foreach (byte x in hash)
        {
            hashString += String.Format("{0:x2}",  x);
        }
        return "0x" + hashString.ToUpper();
    }

Is this acceptable or there is a more appropriate way to do this?

public static string ConvertToHash(string dataToComputeHash)
    {
        var hash = "";
        try
        {
            var keyByte = encoding.GetBytes(key);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                hmacsha256.ComputeHash(encoding.GetBytes(dataToComputeHash));
                hash = ByteToString(hmacsha256.Hash);
            }
        }
        catch (Exception ex)
        {

        }
        return hash;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM