JS: AES encryption and decryption


Library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/aes-js/3.1.2/index.min.js"></script>

Example for CBC mode:

if(typeof aesjs == 'undefined'){
  //npm i aes-js
	var aesjs = require('aes-js');
}

var text = 'WWW.TUTORIALSPOTS.COM';

function _convert1(text){
	var tl = text.length;
  if(tl%16){
    text += "\x00".repeat(16-tl%16)
  }
  return text
}

function _convert2(decryptedText){
	return decryptedText.replace(/[\x00]+$/g,'')
}
 
function _en(text){ 
  text = _convert1(text)  
  var key = [ 11, 21, 32, 4, 45, 36, 27, 8, 9, 210, 111, 12, 13, 14, 15, 16 ];
	var iv = [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];
  var textBytes = aesjs.utils.utf8.toBytes(text);
  var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
  var encryptedBytes = aesCbc.encrypt(textBytes);
  var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);  
  return encryptedHex
}

function _de(encryptedHex){
  var key = [ 11, 21, 32, 4, 45, 36, 27, 8, 9, 210, 111, 12, 13, 14, 15, 16 ];
	var iv = [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];
  var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);
  var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
  var decryptedBytes = aesCbc.decrypt(encryptedBytes);
  var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
  return decryptedText = _convert2(decryptedText)
}

var encryptedHex = _en(text);
var decryptedText = _de(encryptedHex)

console.log(encryptedHex);
//0c657ae6403dff5070b231b0e4a262fe1e0d91df5a8c8e8ffbb59ef9b9d39f7c
console.log(decryptedText);
//WWW.TUTORIALSPOTS.COM

Online demo: https://jsfiddle.net/sans_amour/53vn4gws/

Leave a Reply