Function code for front end encryption using crypto. js

  • 2021-08-06 20:26:37
  • OfStack

crypto-js is a encryption algorithm class library written purely by javascript, which can conveniently hash MD5, SHA1, SHA2, SHA3 and RIPEMD-160 in javascript, and encrypt and decrypt AES, DES, Rabbit, RC4, Triple and DES.

The js can be downloaded on https://github.com/brix/crypto-js of this GitHub, which can separately introduce js with the required encryption method; You can also introduce a file crypto-js. js, which is equivalent to introducing all encryption methods. I use the latter to introduce all encrypted files at one time. This file is not very large and can be accepted.

Because my requirement is reversible encryption, with 1 security (security requirements are not high), so use DES or AES, I use AES:


function getAesString(data,key,iv){// Encryption 
  var key = CryptoJS.enc.Utf8.parse(key);
  var iv  = CryptoJS.enc.Utf8.parse(iv);
  var encrypted =CryptoJS.AES.encrypt(data,key,
    {
      iv:iv,
      mode:CryptoJS.mode.CBC,
      padding:CryptoJS.pad.Pkcs7
    });
  return encrypted.toString();  // Returns the base64 Ciphertext in format 
}
function getDAesString(encrypted,key,iv){// Decryption 
  var key = CryptoJS.enc.Utf8.parse(key);
  var iv  = CryptoJS.enc.Utf8.parse(iv);
  var decrypted =CryptoJS.AES.decrypt(encrypted,key,
    {
      iv:iv,
      mode:CryptoJS.mode.CBC,
      padding:CryptoJS.pad.Pkcs7
    });
  return decrypted.toString(CryptoJS.enc.Utf8);   
}

function getAES(data){ // Encryption 
  var key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; // Key 
  var iv  = '1234567812345678';
  var encrypted =getAesString(data,key,iv); // Ciphertext 
  var encrypted1 =CryptoJS.enc.Utf8.parse(encrypted);
  return encrypted;
}

function getDAes(data){// Decryption 
  var key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; // Key 
  var iv  = '1234567812345678';
  var decryptedStr =getDAesString(data,key,iv);
  return decryptedStr;
}

We can replace key and iv, but we need to ensure that the encryption and decryption of key and iv remain 1


Related articles: