3

I have the following Java code for creating an AES-128 cipher, where key and iv are both based on the same passphrase.

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] keyBytes = new byte[16];
byte[] b = passphare.getBytes("UTF-8");
int len = b.length;
if (len > keyBytes.length) {
    len = keyBytes.length;
}

System.arraycopy(b, 0, keyBytes, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
cipher.init(opmode, keySpec, ivSpec);

cipher.doFinal(textToEncrypt.getBytes("UTF-8"));

I have tried to use the same approach in Javascript using CryptoJS for generating the same cipher, but with no success. Can you please help me?

4
  • Can you provide a short sample input & output? This would make it easier to write & test an equivalent cryptojs version. Also, can you add your current best-effort cryptojs attempt? Commented Jan 21, 2014 at 11:42
  • Yes, sure! This is what I tryed so far jsfiddle.net/jonaix/hgAZM Commented Jan 21, 2014 at 12:29
  • FYI this is not secure. You are converting a password directly into bytes and using that as a key. You should use the password to generate a secure key using a password based key derivation function, like PBKDF or bcrypt or scrypt. Your IV is also not random either, which is not secure. See crypto.stackexchange.com. Commented Jan 21, 2014 at 23:32
  • @JoaoAlmeida with this jsfiddle I am getting error as TypeError: encrypted.ciphertext is undefined Commented Feb 16, 2017 at 7:26

1 Answer 1

1

Quoting the JSFiddle from the OP's comment:

var salt = CryptoJS.lib.WordArray.random(128/8);
// Key and iv should be based on the same value. In this example "1111"
var key = CryptoJS.PBKDF2("1111", salt, { keySize: 128/32 });
var iv = key; // Not sure what should be here!!

You are generating a key from a random salt (see first line), and using that same key as initialization vector... and yet you expect a constant result? (as expected, the result changes in each invocation).

Fix it to use the exact same bytes for key and iv used by the SecretKeySpec and IvParameterSpec from the java code (which you can query using their getEncoded() methods). I do not know whether the AES SecretKeySpec uses PBKDF2 or another key derivation function -- but it should be easy to test. Find the one that matches and stick to it.

Beware also that the default padding in CryptoJS is PKCS7 (see the docs on "block modes and padding"); this may differ strongly from the PKCS5 that you specify in your first line of Java code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.