Decrypt file in javascript which is encrypted from Java

Viewed 61

I have encrypted a file using the following code: Functions to generate key and iv

public static SecretKey generateKey(int i) {
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(i);
        SecretKey key = keyGenerator.generateKey();
        return key;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

public static IvParameterSpec generateIv() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);
    return new IvParameterSpec(iv);
}

Below is the encryption part.

String algorithm = "AES/CBC/PKCS5Padding";

SecretKey userkey = GeneralUtil.generateKey(128);
byte[] userKeyEncoded = userkey.getEncoded();

System.out.println("userKeyEncoded "+new String(userKeyEncoded));
String userencodedKey = Base64.getEncoder().encodeToString(userkey.getEncoded());// to save in DB

IvParameterSpec userivParameterSpec = GeneralUtil.generateIv();

String userencodedIv = Base64.getEncoder().encodeToString(userivParameterSpec.getIV());// to save in DB

System.out.println("userencodedKey" + userencodedKey + "userencodedIv" + userencodedIv);

cipher.init(Cipher.ENCRYPT_MODE, userkey, userivParameterSpec);
byte[] encryptedByte = cipher.doFinal(decryptedByte);

And I am encoding it

byte[] finalencodedfile = Base64.getEncoder().encode(encryptedByte);

Finally, in the client side I am receiving this finalencodedfile with encodedkey and encoded iv.

How will I decrypt it from javascript using Cryptojs?The thing I have done so far is:

const bytes = CryptoJS.AES.decrypt({ciphertext: encodedFile}, encodedKey, {
  iv: encodedIv,
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Pkcs7,
});

I think I am missing some thing in the JavaScript portion while decoding key and IV.

0 Answers
Related