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 });
yanana
  • 2,241
  • 2
  • 18
  • 28
Arun
  • 1,528
  • 3
  • 19
  • 34
  • 1
    Duplicate of http://stackoverflow.com/questions/19436882/different-output-encryption-both-cryptojs-and-java-code?rq=1. http://stackoverflow.com/questions/22607791/aes-encryption-using-java-and-decryption-using-javascript?rq=1 – SatyaTNV Jul 13 '15 at 04: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. – pvg Jul 13 '15 at 04: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? – Arun Jul 13 '15 at 04: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. – Artjom B. Jul 13 '15 at 05:54

0 Answers0