Hi all,
I am trying to emulate an encryption algorithm from C# in Delphi but keep coming up with different results.
The C# function goes like this (And I can’t change it without causing all sorts of issues):
using System.Text;
using System.Security.Cryptography;
static string Encrypt(string cleanString)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
return BitConverter.ToString(hashedBytes);
}
Console.WriteLine(Encrypt("FredtheNed"));
which produces a result of:
66-F6-C6-07-9B-44-78-BE-A4-B0-6A-7B-66-3B-97-FF
A try in Delphi:
uses IdHashMessageDigest;
function Encrypt: string;
var
idmd5 : TIdHashMessageDigest5;
begin
idmd5 := TIdHashMessageDigest5.Create;
try
Result := idmd5.HashString('FredtheNed');
finally
idmd5.Free;
end;
end;
Produces a result of:
81FC4410079C7004A22523F7886E9899
Which, apart from the dashes is obviously very different. Any ideas?
I have tried a number of different libraries in Delphi but they all return the same.
or getting the bytes as you do in the c# code would sort it out
bytes := IndyTextEncoding_UTF16LE.GetBytes(data);
Result := idmd5.HashBytesAsHex(bytes);
There are a number things that are worth noting with your example:
Be wary of mixing the terms Encrypt and Hash, these are pure hash functions.
When dealing with hashing functions you’re talking about bytes, being explict is specifying the encoding is very important and should not be left to underlying layers to guess what types of bytes you want to derive from a string or you’re going to end up with unexpected hashes / mismatched hashes. The way that you’ve done the code in C# is better than passing a string into a hash function which needs to select a encoding to use. Allowing underlying layers to determine those specifics may mean that if your code is run on different OS platforms or compilers will result in differing hashes.