CryptoJS alternative to crypto.createHash('md5').update(input).digest();

I’m trying to generate a UUID from a string, I basically want to recreate what UUID.nameUUIDFromBytes does in Java. I found this article that works perfect outside of postman, Java's UUID.nameUUIDFromBytes to written in JavaScript? - Stack Overflow

but crypto is not available in Postman. I’ve also tried CryptoJS in postman and have gotten really close, the generated UUID is off by a single character…

function javaHash(test) {
    var md5Bytes = CryptoJS.MD5(test);
    console.log(md5Bytes);

    md5Bytes[6] &= 0x0f;  /* clear version        */
    md5Bytes[6] |= 0x30;  /* set to version 3     */
    md5Bytes[8] &= 0x3f;  /* clear variant        */
    md5Bytes[8] |= 0x80;  /* set to IETF variant  */
    console.log(md5Bytes);

    return md5Bytes.toString(CryptoJS.enc.Hex).replace(/-/g, "").replace(/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/, "$1-$2-$3-$4-$5");
}

console.log(javaHash('123456789'));

From looking at the value in the console it doesnt look like the value is being changed by whatever magic is supposed to happen in the middle of the method.

I’ve also tried importing crypto from here: https://cdnjs.com/libraries/crypto-js, with this method: Adding External Libraries in Postman | Postman Blog

function javaHash(test) {
   eval(pm.collectionVariables.get("crypto_library"));
    
    let md5Bytes = this.crypto.createHash('md5').update(test).digest();
    console.log(md5Bytes);

    md5Bytes[6] &= 0x0f;  /* clear version        */
    md5Bytes[6] |= 0x30;  /* set to version 3     */
    md5Bytes[8] &= 0x3f;  /* clear variant        */
    md5Bytes[8] |= 0x80;  /* set to IETF variant  */
    console.log(md5Bytes);

    return md5Bytes.toString(CryptoJS.enc.Hex).replace(/-/g, "").replace(/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/, "$1-$2-$3-$4-$5");
}

but I get an error “There was an error in evaluating the Pre-request Script:TypeError: Cannot read properties of undefined (reading ‘lib’)”

Any ideas?

I got a working answer on Stack Overflow

Sounds like you resolved the issue. Here’s other code samples for using CryptoJS in Postman. And feel free to contribute your example via PR if you think others can benefit from it: Postman

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.