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=
CodePudding user response:
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
)