Saturday, March 24, 2012

MD5 hashing and data types

I'm trying to MD5 hash a string, and then POST (in a HTML form) the result in a HTML text (i.e. 'input') box. How do I manage the data types? My 'source' is a string, and my input box value has to be a string (the form is rendered & submitted via a Literal control). What about the middle stages? Doesn't the hashed value use the Byte data type in some way?You can convert they byte array to a string. Since some of the bytes represent non-printable characters, you may want to convert to a Base64 string like so:

MD5 md5CSP = new MD5CryptoServiceProvider();
byte[] HashResult = md5CSP.ComputeHash(DataToHash);
string HashString = Convert.ToBase64String(HashResult);

Hope that helps
The data I want to convert is a string. When I try the above, I get an error message. Any suggestions? Could I convert the string (DataToHash) to something else, in the same way that HashResult was changed with a Convert.To..., above?

"...

Overload resolution failed because no accessible 'ComputeHash' can be called with these arguments:

'Public Overloads Function ComputeHash(buffer() as byte) as byte()': Value of type 'String' cannot be converted to '1-dimensional array of Byte'.

'Public Overloads Function ComputeHash(inputstream as System.IO.Stream) as byte()': Value of type 'String' cannot be converted to System.IO.Stream'.

..."
Sorry, I wasn't checking my Hotmail account as frequently as I normally do.

Yes, you can convert your string to a byte array:

byte[] DataBytes = System.Text.Encoding.ASCII.GetBytes(DataString);

You could also use UTF8, etc.
You could use :

string myHash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("yourpassword", "md5");

This uses string throughout.

No comments:

Post a Comment