how to use CryptoJS in javascript

zhaowweny picture zhaowweny · Jun 24, 2018 · Viewed 51.2k times · Source

I used CryptoJS instead of nodejs crypto module because I just use the native JavaScript,but some codes can't work:

function aesEncrypt(text, secKey) {
  const _text = text
  const lv = new Buffer('0102030405060708', 'binary')
  const _secKey = new Buffer(secKey, 'binary')
  const cipher = crypto.createCipheriv('AES-128-CBC', _secKey, lv)
  let encrypted = cipher.update(_text, 'utf8', 'base64')
  encrypted += cipher.final('base64')
  return encrypted
}

So how should I modify these codes?

Answer

Melchia picture Melchia · Jun 24, 2018

Here's a sample on how to use CryptoJs in webclient:

// INIT
var myString   = "blablabla Card game bla";
var myPassword = "myPassword";

// PROCESS
var encrypted = CryptoJS.AES.encrypt(myString, myPassword);
var decrypted = CryptoJS.AES.decrypt(encrypted, myPassword);
document.getElementById("demo0").innerHTML = myString;
document.getElementById("demo1").innerHTML = encrypted;
document.getElementById("demo2").innerHTML = decrypted;
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
</head>


  
  <strong><label>Original String:</label></strong>
  <span id="demo0"></span>

  <br>
  <br>
  
  <strong><label>Encrypted:</label></strong>
  <span id="demo1"></span>

  <br>
  <br>
  
  <strong><label>Decrypted:</label></strong>
  <span id="demo2"></span>

  <br> 
  <br>

  <strong><label>String after Decryption:</label></strong>
  <span id="demo3"></span>

  
  <br />
  <br />
 

NB:

You might want to use CDN if you don't want to use node modules.