Goal: Simple CryptoJS example to encrypt, decrypt using AES-128, ECB, 0-padding.
See below my runnable sample.
Input text is "US0378331005-USD-US-en" which is encrypted (hopefully AES-128 with all the above) and then decrypted (which does not work)
text: US0378331005-USD-US-en
key: 11A1764225B11AA1
key length: 16
encrypted 951422f8ac8354acf23fbc
decrypted a5126fa0fc3cb4c39a4f3e637be98a73
var text = 'US0378331005-USD-US-en';
var key = '11A1764225B11AA1'; // to ensure AES-128 this has to be 16 bit
console.log('text:', text);
console.log('key:', key);
console.log('key length:', key.length );
text = CryptoJS.enc.Hex.parse(text);
key = CryptoJS.enc.Hex.parse(key);
var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
var encrypted = CryptoJS.AES.encrypt(text, key, { iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding });
encrypted = encrypted.ciphertext.toString(CryptoJS.enc.Hex);
console.log('encrypted', encrypted);
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding });
console.log('decrypted', decrypted.toString() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/aes.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/md5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/enc-hex.min.js"></script>
There are several bugs in your code:
As fix, padding must be applied. Since you are talking about 0-padding, you may mean zero padding, i.e.
CryptoJS.pad.ZeroPadding. Note that PKCS#7 padding (the default) is more reliable.As fix, for instance, a 32 hex digit key must be used for AES-128 in combination with the Hex encoder. Another alternative that works with the posted key is the Utf8 encoder.
As fix the Utf8 encoder is to be used.
CryptoJS.AES.decrypt()expects aCipherParamsobject, but in the current code the hex encoded ciphertext is passed.The fix is to either create a
CipherParamsobject from the hex encoded ciphertext and pass it, or to pass the Base64 encoded ciphertext, which CryptoJS implicitly converts to aCipherParamsobject.Fixed code: