Search code examples
javascriptjavamd5cryptojs

How to get Java DigestUtils.md5() output from Javascript?


Java code that uses Apache Commons library to generate signature:

byte[] md5 = DigestUtils.md5("test");
String signature = Base64.encodeBase64String(md5);
System.out.println(signature);
// CY9rzUYh03PK3k6DJie09g==

Javascript code I am trying to write to get the same output:

const md5 = CryptoJS.MD5("test");
const signature = btoa(md5);
console.log(signature);
// MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=

I know how to get the same output if I change the Java code like this:

String md5 = DigestUtils.md5Hex("test");
String signature = Base64.encodeBase64String(md5.getBytes(StandardCharsets.UTF_8));
System.out.println(signature);
// MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=

But unfortunately I am not allowed to modify Java code, so how can I modify Javascript code instead, to get the same output as Java code?


Solution

  • I think I found the solution by myself:

    const md5 = CryptoJS.MD5("test");
    const signature = md5.toString(CryptoJS.enc.Base64);
    console.log(signature);
    // CY9rzUYh03PK3k6DJie09g==