3

I am getting an encrypted key which is generated using Java. I need to decrypt it in AngularJS app using CryptoJS. I had done similar thing using node but now in Angular I am stuck. This fiddle http://jsfiddle.net/s5g82rqh/ is what I have tried so far but it returns empty.

Below is what I have tried till now

 function decrypt_core_AES_CBC(password, ciphertext) { var iv = CryptoJS.lib.WordArray.random(128/8); var message = CryptoJS.AES.decrypt(ciphertext, password, { mode: CryptoJS.mode.CBC, iv: password }); console.log("The current iv is: " + iv.toString() ); return CryptoJS.enc.Utf8.stringify(message); } var data = '6615702f2dd672f643fd57623d6362a510a98faf4b1c068fd468b525a5fa5471809852a0f9cb7936ce3d3892c233b8c48ce2608f16ce6fa66005b2d97689fbb4'; var key = '3426D38AB846B62B9C236D288778D997'; var dec = decrypt_core_AES_CBC(key, data); console.log(dec); 

Below is the node.js code which works for me. I have no success in achieving similar in CryptoJS. As per my understanding crypto comes as built-in library which node has its own wrapper on top of it.

var crypto = require('crypto'); var defaultAlgorithm= 'aes-128-cbc'; var defaultFormat= 'hex'; var ivLength= 16; function decode (data, key, algorithm, format) { // Make sure the data is a buffer object if (data instanceof Buffer) { data = data.toString(); } // Get defaults if needed algorithm = algorithm || defaultAlgorithm; format = format || defaultFormat; ivLength = ivLength * 2; // Get the initialization vector var iv = new Buffer(data.substring(0, ivLength), 'hex'); // Remove the iv from the data data = data.substring(ivLength); var decipher = crypto.createDecipheriv(algorithm, new Buffer(key, 'hex'), iv); var decrypted = decipher.update(data, format, 'utf8') + decipher.final('utf8'); return decrypted; } var data ='6615702f2dd672f643fd57623d6362a510a98faf4b1c068fd468b525a5fa5471809852a0f9cb7936ce3d3892c233b8c48ce2608f16ce6fa66005b2d97689fbb4'; var key = '3426D38AB846B62B9C236D288778D997'; var dec = decode(data, key, defaultAlgorithm, defaultFormat); console.log(dec); 
0

2 Answers 2

9

You have three issues:

  • CryptoJS supports two types of encryption/decryption: key derived from a password and directly passed key. You want to do this from a key, so you need to parse the hex-encoded key string into CryptoJS' native format before passing it to the decrypt() function:

    key = CryptoJS.enc.Hex.parse(key); 

    Also, don't confuse a key with a password.

  • You forgot to slice off the IV from the ciphertext before decrypting.

    var iv = CryptoJS.enc.Hex.parse(ciphertext.slice(0, 32)); ciphertext = CryptoJS.enc.Hex.parse(ciphertext.slice(32)); 
  • CryptoJS' expects either a CipherParams object or an OpenSSL-formatted string to decrypt from. Since you only have a hex string, you have to parse it before use and use it like this:

    var message = CryptoJS.AES.decrypt({ ciphertext: ciphertext }, key, { iv: iv }); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your interest. I tried your suggestion and it seems like I am too close solve this. I console log message variable and its giving array of words but now when I am trying to stringify it using CryptoJS.enc.Utf8 it gives me empty result. Updated fiddle jsfiddle.net/5k1vtz77/1 Your suggestion would be highly appreciated. Thanks again!
Sorry, I forgot parsing the ciphertext. The output is "1280c6dc-4a17-4b75-aa83-f4ce224cfbce".
Here is an updated version of the fiddle that works: jsfiddle.net/fyodgw58/1
1

It took one week for me to find out working code for aes-128-cbc in Java, PHP and Java Script. I had to search alot at various website. Finally with multiple hit and trial below code worked out for me. Both encryption and decryption. Encrypt in Java; Decrypt in PHP or JavaScript, Encrypt in PHP; Decrypt in Java or JavaScript, Encrypt in JavaScript Decrypt in PHP or Java. All option will work

The length of Key will be 16 digit having Alpha-numeric values. Use Same key to encrypt and decrypt data. IV is 16 digit Random value of Alpha-numeric to be passed while encryption.

PHP code for Encryption and Decryption:

 function encrypt($key, $iv, $data) { static $OPENSSL_CIPHER_NAME = "aes-128-cbc"; //Name of OpenSSL Cipher static $CIPHER_KEY_LEN = 16; //128 bits if (strlen($key) < $CIPHER_KEY_LEN) { $key = str_pad("$key", $CIPHER_KEY_LEN, "0"); //0 pad to len 16 } else if (strlen($key) > $CIPHER_KEY_LEN) { $key = substr($str, 0, $CIPHER_KEY_LEN); //truncate to 16 bytes } $encodedEncryptedData = base64_encode(openssl_encrypt($data, $OPENSSL_CIPHER_NAME, $key, OPENSSL_RAW_DATA, $iv)); $encodedIV = base64_encode($iv); $encryptedPayload = $encodedEncryptedData.":".$encodedIV; return $encryptedPayload; } function decrypt($key, $data) { // $key = $request['key']; // $data = $request['data']; static $OPENSSL_CIPHER_NAME = "aes-128-cbc"; //Name of OpenSSL Cipher static $CIPHER_KEY_LEN = 16; //128 bits if (strlen($key) < $CIPHER_KEY_LEN) { $key = str_pad("$key", $CIPHER_KEY_LEN, "0"); //0 pad to len 16 } else if (strlen($key) > $CIPHER_KEY_LEN) { $key = substr($str, 0, $CIPHER_KEY_LEN); //truncate to 16 bytes } $parts = explode(':', $data); //Separate Encrypted data from iv. $decryptedData = openssl_decrypt(base64_decode($parts[0]), $OPENSSL_CIPHER_NAME, $key, OPENSSL_RAW_DATA, base64_decode($parts[1])); return $decryptedData; } 

Java Code for Encryption and Decryption

 import android.util.Base64; import android.util.Log; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Java_AES_Cipher { private static String CIPHER_NAME = "AES/CBC/PKCS5PADDING"; private static int CIPHER_KEY_LEN = 16; //128 bits /** * Encrypt data using AES Cipher (CBC) with 128 bit key * * * @param key - key to use should be 16 bytes long (128 bits) * @param iv - initialization vector * @param data - data to encrypt * @return encryptedData data in base64 encoding with iv attached at end after a : */ public static String encrypt(String key, String iv, String data) { try { if (key.length() < Java_AES_Cipher.CIPHER_KEY_LEN) { int numPad = Java_AES_Cipher.CIPHER_KEY_LEN - key.length(); for(int i = 0; i < numPad; i++){ key += "0"; //0 pad to len 16 bytes } } else if (key.length() > Java_AES_Cipher.CIPHER_KEY_LEN) { key = key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes } IvParameterSpec initVector = new IvParameterSpec(iv.getBytes("ISO-8859-1")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ISO-8859-1"), "AES"); Cipher cipher = Cipher.getInstance(Java_AES_Cipher.CIPHER_NAME); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, initVector); byte[] encryptedData = cipher.doFinal((data.getBytes())); String base64_EncryptedData = Base64.encodeToString(encryptedData, Base64.DEFAULT); String base64_IV = Base64.encodeToString(iv.getBytes("ISO-8859-1"), Base64.DEFAULT); base64_EncryptedData = base64_EncryptedData.replaceAll(System.getProperty("line.separator"), ""); base64_IV = base64_IV.replaceAll(System.getProperty("line.separator"), ""); Log.i("Java_AES_Cipher","Encrypted data is "+ base64_EncryptedData + ":" + base64_IV); return base64_EncryptedData + ":" + base64_IV; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Decrypt data using AES Cipher (CBC) with 128 bit key * * @param key - key to use should be 16 bytes long (128 bits) * @param data - encrypted data with iv at the end separate by : * @return decrypted data string */ public static String decrypt(String key, String data) { try { if (key.length() < Java_AES_Cipher.CIPHER_KEY_LEN) { int numPad = Java_AES_Cipher.CIPHER_KEY_LEN - key.length(); for(int i = 0; i < numPad; i++){ key += "0"; //0 pad to len 16 bytes } } else if (key.length() > Java_AES_Cipher.CIPHER_KEY_LEN) { key = key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes } String[] parts = data.split(":"); if (parts.length<2) { Log.i("Java_AES_Cipher","Length "+ parts.length); return data; } IvParameterSpec iv = new IvParameterSpec(Base64.decode(parts[1], Base64.DEFAULT)); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ISO-8859-1"), "AES"); Cipher cipher = Cipher.getInstance(Java_AES_Cipher.CIPHER_NAME); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] decodedEncryptedData = Base64.decode(parts[0], Base64.DEFAULT); byte[] original = cipher.doFinal(decodedEncryptedData); return new String(original); } catch (Exception ex) { ex.printStackTrace(); } return null; } 

Java Script Code for Encryption and Decryption

 <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script> function encrypt (messageText,key, iv){ var message = messageText; var key = CryptoJS.enc.Utf8.parse(key); var iv = CryptoJS.enc.Utf8.parse(iv); var encrypted = CryptoJS.AES.encrypt( message,key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 } ); this.encrypted = CryptoJS.enc.Base64.stringify(encrypted.ciphertext); console.log('encrypted:'+encrypted); return encrypted; } function decrypt(keyBase64, messagebase64) { const digest = messagebase64.split(':'); const crypttext = CryptoJS.enc.Base64.parse(digest[0]) const ivBase64 = CryptoJS.enc.Base64.parse(digest[1]) const decrypted = CryptoJS.AES.decrypt( { ciphertext: crypttext }, CryptoJS.enc.Utf8.parse(keyBase64), { iv: ivBase64, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 } ); console.log('decrypted: '+decrypted.toString(CryptoJS.enc.Utf8)); return decrypted.toString(CryptoJS.enc.Utf8); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.