Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect decryption output when using CryptoJS library for AES

I am trying to encrypt and decrypt some random data using AES. I can successfully encrypt data using the following code,

function padString(source) {
  var paddingChar = 'x';
  var size = 16;
  var padLength = size - source.length;

  for (var i = 0; i < padLength; i++) source += paddingChar;

  return source;
}

var key = CryptoJS.enc.Hex.parse('dassdadsasad');
var iv = CryptoJS.enc.Hex.parse('fedcba9876543210');
var message = "0x72648174091c3f7cd41773f636ca9a15756798";
var padMsg = padString(message);

var encrypted = CryptoJS.AES.encrypt(padMsg, key, {
  iv: iv,
  padding: CryptoJS.pad.NoPadding,
  mode: CryptoJS.mode.CBC
});

but when I try to decrypt it,

var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
  iv: iv,
  padding: CryptoJS.pad.NoPadding,
  mode: CryptoJS.mode.CBC
});

I get the incorrect output for decryption instead of getting back my plain text. Here is the output for instance,

Message: "0x72648174091c3f7cd41773f636ca9a15756798" 40

Padded message: "0x72648174091c3f7cd41773f636ca9a15756798" 40

Encrypted: 8qCjEtSLhchErbhJu8jo/xy8T5T1eSAFazuWLKwKdAW9F0ZUjJLlZw==

Encrypted text: f2a0a312d48b85c844adb849bbc8e8ff1cbc4f94f57920056b3b962cac0a7405bd1746548c92e567

Decrypted c748c55c0212d1688e79de5f00379eb0d802789501e6cbab3e6255b902eaa528a40d32123bcd0ce1

Can someone please tell me what am I doing wrong or if I am missing something ?

Here is the live demonstration, https://jsfiddle.net/4zb9hrxb/267/

like image 940
aes256 Avatar asked Nov 22 '25 16:11

aes256


1 Answers

Your key is invalid:

var key = CryptoJS.enc.Hex.parse('dassdadsasad');

does not make much sense in the first place since s does not exist in hexadecimal notation. Either specify a 256 bit key as hex, like this:

key = CryptoJS.enc.Hex.parse("123456789012345678901234567890ab");

(note: only hexadecimal characters) or let CryptoJS derive the key from a passphrase:

var key = 'dassdadsasad';
like image 79
phihag Avatar answered Nov 24 '25 07:11

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!