PROWAREtech

articles » archived » asp-net » hash-based-message-authentication-code

ASP.NET: Hash-based Message Authentication Code

Safely store user passwords (.NET Framework).

Use a hash to secure a site. For example, this can be used to compute a hash based on all the parameters of a GET request (QueryString parameters) to prevent users or hackers from tampering with the parameters. Also, this can be used for storing passwords. Generate a unique key using a GUID.

Imports System.Security.Cryptography

Function MakeHashCode(ByVal sMessageToCompute As String) As String
	'key:8a7eff51-db15-44c7-a3c2-ddeb2053f051 THIS SHOULD BE UNIQUE TO EACH SITE
	Dim hmac256 As HMACSHA256
	hmac256 = New HMACSHA256(Encoding.UTF8.GetBytes("8a7eff51-db15-44c7-a3c2-ddeb2053f051"))
	hmac256.ComputeHash(Encoding.UTF8.GetBytes(sMessageToCompute))
	Dim i As Integer
	MakeHashCode = ""
	For i = 0 To hmac256.Hash.Length - 1
		MakeHashCode &= hmac256.Hash(i).ToString("X2")
	Next i
End Function
string MakeHashCode(string sMessageToCompute)
{
	//key:8a7eff51-db15-44c7-a3c2-ddeb2053f051 THIS SHOULD BE UNIQUE TO EACH SITE
	System.Security.Cryptography.HMACSHA256 hmacsha256;
	hmacsha256 = new System.Security.Cryptography.HMACSHA256(
		Encoding.UTF8.GetBytes("8a7eff51-db15-44c7-a3c2-ddeb2053f051"));
	hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(sMessageToCompute));
	int i;
	string returnString = "";
	for(i = 0; i < hmacsha256.Hash.Length; i++)
	{
		returnString += hmacsha256.Hash[i].ToString("X2");
	}
	return returnString;
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE