Call require and crypto functions

I have added cryptojs and requirejs scripts to my project settings > code section but are unable to call their functions:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

For example I need to create a md5 hash signature for a header of a GET request for a payment gateway, when I call the function it results in undefined function:

//this line results in cryptoJS is not defined

return cryptoJS.createHash(“md5”).update(getString).digest(“hex”);

const cryptoJS = require([crypto]);

const generateSignature = (data, passPhrase = null) => {
// Create parameter string
let pfOutput = “”;
for (let key in data) {
if(data.hasOwnProperty(key)){
if (data[key] !== “”) {
pfOutput +=${key}=${encodeURIComponent(data[key].trim()).replace(/%20/g, " + ")}&
}
}
}

// Remove last ampersand
let getString = pfOutput.slice(0, -1);
if (passPhrase !== null) {
getString +=&passphrase=${encodeURIComponent(passPhrase.trim()).replace(/%20/g, "+")};
}

return cryptoJS.createHash(“md5”).update(getString).digest(“hex”);
};

myData.signature = generateSignature(myData);

Any help will be appreciated. Thanks

Hello @Mancha!

There are probably two problems with your code:

  1. You’ve connected the script right, however here’s how you should refer to your library in the script: CryptoJS

  2. You might probably be trying to use the wrong library. The library you use doesn’t contain such methods: cryptoJS.createHash(“md5”).update(getString).digest(“hex”);

One of our developers has tried to help you, and here’s the code snippet he’s prepared (with the comments):

const myData ={{data}}

const generateSignature = (data, passPhrase = null) => {
// Create parameter string
  let pfOutput = '';
  for (let key in data) {
    if(data.hasOwnProperty(key)){
      if (data[key] !== '') {
          pfOutput +=`${key}=${encodeURIComponent(data[key].trim()).replace(/%20/g, " + ")}&`
      }
    }
  }

  // Remove last ampersand
  let getString = pfOutput.slice(0, -1);
  if (passPhrase !== null) {
  getString +=`&passphrase=${encodeURIComponent(passPhrase.trim()).replace(/%20/g, "+")}`;
  }
  // reference lib below as CryptoJS (window.CryptoJS)
  // Find docs here: https://github.com/brix/crypto-js
  return CryptoJS.MD5();
  /**
    The code below will not work, cause it looks like this is example of usage of Node.js "crypto" module
    "crypto-js" you've added is another library

    return CryptoJS.createHash("md5").update(getString).digest("hex");
  */
};

myData.signature = generateSignature(myData);

I hope it helps!
If not, please let us know. Thank you :slight_smile:

1 Like

Hi @ev_jennie

Thank you, I managed to resolve this yesterday and forgot to update the thread, however I am facing a different issue now where this lib won’t work on the exported project because it conflicts with another crypto library in the angular-cli, support are assisting me via email.

Thank you kindly.

1 Like