1

I have Java code which does AES and I am trying to implement same in jQuery using cryptoJs. But the output varies in jQuery. I am not able to figure it out where I am doing it wrong. I am new to encryption, please help me out.

Java Code

public static String Encrypt(String text, String key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] keyBytes = new byte[16];
    byte[] b = key.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(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

    byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
    String result = Base64.encodeToString(results, 0);
    return result;
}

JavaScript Code

var plainText = "abc"
var password = "password";
var key = CryptoJS.enc.Hex.parse(password);
var iv = CryptoJS.enc.Hex.parse(password);

var encrypted = CryptoJS.AES.encrypt(plainText, key, { iv: iv });
4
  • 1
    Duplicate of stackoverflow.com/questions/19436882/…. stackoverflow.com/questions/22607791/… Commented Jul 13, 2015 at 4:21
  • 2
    This code is an excellent example of why you should not roll your own crypto. Please don't do this, it's quite terribly broken - you're using the same value for key and iv, for instance. Commented Jul 13, 2015 at 4:24
  • @Satya, I checked that, and I was confused. The key I can use the password, but what about iv. How do i decide on that? Commented Jul 13, 2015 at 4:40
  • 1
    A key is not a password, because it has to be 16, 24 or 32 bytes long. Use a proper key derivation function like PBKDF2. Commented Jul 13, 2015 at 5:54

0

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.