I have following two functions for encrypting and decrypting in JavaScript.
the keys in below functions are not identical because the server side is programmed accordingly.
function encryptData(data_to_encrypt){
var key = CryptoJS.enc.Hex.parse('0123456789abcdef0123456789abcdef');
var iv = CryptoJS.enc.Hex.parse('abcdef9876543210abcdef9876543210');
var encrypted = CryptoJS.AES.encrypt((data_to_encrypt), key, { iv: iv });
var encrypted_data = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
return encrypted_data;
}
function decryptData(data_to_decrypt){
var keyBase64 = CryptoJS.enc.Base64.parse("ITU2NjNhI0tOc2FmZExOTQ==");
var iv1 = CryptoJS.enc.Base64.parse('AAAAAAAAAAAAAAAAAAAAAA==');
var bytes = CryptoJS.AES.decrypt(data_to_decrypt, keyBase64, {iv: iv1}, {mode: CryptoJS.mode.CBC});
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
return plaintext;
}
I want to do this in android API 19 and +.
I tried to achieve it with solution given here
https://stackoverflow.com/a/41434590/2173890
but could not figure out how and where to pass "key" and "iv".
So, I tried with this code:
String strToEncrypt = "hello world. i am new bee.";
try {
String strEncrypted = openssl_encrypt(strToEncrypt, "0123456789abcdef0123456789abcdef", "abcdef9876543210abcdef9876543210");
String strDecrypted = openssl_decrypt(strEncrypted, "0123456789abcdef0123456789abcdef", "abcdef9876543210abcdef9876543210");
System.out.println(strDecrypted);
} catch (Exception e) {
e.printStackTrace();
}
private String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(strIv.getBytes(), 0, ciper.getBlockSize());
ciper.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encryptedCiperBytes = ciper.doFinal(data.getBytes());
String s = new String(encryptedCiperBytes);
System.out.println("Ciper : " + s);
return s;
}
private String openssl_decrypt(String input, String strKey, String strIv) {
String s = null;
try {
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(strIv.getBytes(), 0, ciper.getBlockSize());
ciper.init(Cipher.DECRYPT_MODE, key, iv);
byte[] encryptedCiperBytes = ciper.doFinal(input.getBytes());
s = new String(encryptedCiperBytes);
System.out.println("Ciper : " + s);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
but openssl_decrypt throws error:
javax.crypto.IllegalBlockSizeException: error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH
I have tried the above with identical keys "strKey".
The javascript functions are working fine.
I want exact parallel function in java
that too compatible with old Java version so that I can implement it in android API 19.