When using CAPICOM in Classic ASP (VBScript) to perform MD5 hashing like so:
With server.CreateObject("CAPICOM.HashedData")
.Algorithm = 3 ' CAPICOM_HASH_ALGORITHM_MD5
.Hash "password"
md5Pwd = .Value
End With
I get this result: B081DBE85E1EC3FFC3D4E7D0227400CD
When I use .NET, I get this result: 5f4dcc3b5aa765d61d8327deb882cf99
Why are the MD5 strings different? What am I doing wrong?
Here is my C# function:
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash( Encoding.Default.GetBytes( val ) );
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for( int i = 0; i < data.Length; i++ ) {
sBuilder.Append( data[i].ToString( "x2" ) );
}
// Return the hexadecimal string.
return sBuilder.ToString();
The problem is that you are using
Encoding.Defaultencoding which represents 7 bit ASCII characters. At the same time, “CAPICOM manipulates only Unicode strings while validating and generating digital signatures”.So,
Encoding.Default.GetBytesdeals with one-byte characters (losing any non-ASCII data by the way), while CAPICOM.HashedData treats them as 2-byte Unicode characters.Replace
Encoding.DefaultwithEncoding.Unicodeto make your .NET implementation to be compatible with CAPICOM.One more note, use
data[i].ToString("X2")to produce upper-case result, as you have in CAPICOM implementation.