0

I am trying to convert JavaScript CryptoJS.enc.Base64 equivalent C#. My staring string is "mickeymouse". The toMD5 JavaScript code produces matched the C# code with the result of: 98df1b3e0103f57a9817d675071504ba

However, the toB64 code results in two different results for JavaScript vs C#.

JavaScript toB64 RESULT: mN8bPgED9XqYF9Z1BxUEug==

C# toB64 RESULT: OThkZjFiM2UwMTAzZjU3YTk4MTdkNjc1MDcxNTA0YmE==

What is the JavaScript CryptoJS.enc.Base64 equivalent C# so I can get the same results in C#?

            // Javascript
            // var toMD5 = CryptoJS.MD5("mickeymouse");
            // toMD5 RESULT: 98df1b3e0103f57a9817d675071504ba

            // C# (match with js)
            var toMD5 = CreateMD5("mickeymouse");
            // toMD5 RESULT: 98df1b3e0103f57a9817d675071504ba


            // Javascript
            // var toB64 = toMD5.toString(CryptoJS.enc.Base64);
            // toB64 RESULT:  mN8bPgED9XqYF9Z1BxUEug==

            // C# (not matched with js)
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(toMD5);
            var toB64 = System.Convert.ToBase64String(plainTextBytes);
            // toB64 RESULT:  OThkZjFiM2UwMTAzZjU3YTk4MTdkNjc1MDcxNTA0YmE=
Ravi Ram
  • 24,078
  • 21
  • 82
  • 113
  • 1
    In C#, you seem to be base64-encoding an already hex-encoded string. If that's what your `CreateMD5` function returns and you can't change it, then see https://stackoverflow.com/questions/46327156/convert-a-hex-string-to-base64 to first un-hex-encode the MD5 result and then base64-encode it. – CherryDT Oct 06 '21 at 17:12

1 Answers1

1

Not sure what your CreateMD5 function does, but calculating MD5 bytes and passing them directly to Convert.ToBase64String produces expected result:

using var md5 = MD5.Create();
var hash = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes("mickeymouse"));
Console.WriteLine(Convert.ToBase64String(hash) == "mN8bPgED9XqYF9Z1BxUEug==");// prints True

If you still need to use CreateMD5 - use reverse algorithm to what was used to turn bytes into string, not just System.Text.Encoding.UTF8.GetBytes (cause System.Text.Encoding.UTF8.GetString(hash) produces different result compared to CreateMD5)

Guru Stron
  • 102,774
  • 10
  • 95
  • 132