2
votes

I have a code in Java (Android) to encrypt plaintext to ciphertext using aes-128-cbc. I am able to decrypt this ciphertext to its corresponding plaintext in PHP but not in Java itself.

The Java code for encryption is as below,

String iv = "0000000000000000"; //Ignore security concerns
IvParameterSpec ivspec;
ivspec = new IvParameterSpec(iv.getBytes());

String plaintext = "Top Secret Data";
byte[] encrypted = null;

Cipher cipher;
cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, seckey, ivspec);
encrypted = cipher.doFinal(padString(plaintext).getBytes());

ciphertext = Base64.encodeToString(encrypted, Base64.DEFAULT);

Log.i("Encrypted Base64 Data", ciphertext);

The corresponding PHP code which is able to decrypt this successfully is as below,

public function decrypt($data)
{
    $key = $_SESSION['sessionkey'];
    $iv = "0000000000000000";
    $data = base64_decode($data);

    $encobj = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
    mcrypt_generic_init($encobj, $key, $iv);
    $decrypted = mdecrypt_generic($encobj, $data);

    mcrypt_generic_deinit($encobj);
    mcrypt_module_close($encobj);

    return utf8_encode(trim($decrypted));
}

The problematic Java code for decryption which reverses to the wrong plaintext is as below

String iv = "0000000000000000";
IvParameterSpec ivspec;
ivspec = new IvParameterSpec(iv.getBytes());

byte[] decrypted = null;

Cipher cipher;
cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, seckey, ivspec);
decrypted = cipher.doFinal(Base64.decode(ciphertext, Base64.DEFAULT));
Log.i("Decrypted Data",decrypted.toString());

I would appreciate it if someone could point out what's wrong with the Java decryption code.

1
i guess there is a similarity between your encryption and your decryption code in java: so isn't decrypted a byte array (byte[])? In this case you might need the string conversion as follows: String resp = new String(decrypted) - user4624062

1 Answers

2
votes

Try this

  Cipher cipher;
  cipher = Cipher.getInstance("AES/CBC/NoPadding");
  cipher.init(Cipher.DECRYPT_MODE, seckey, ivspec);
  decrypted = cipher.doFinal(Base64.decode(ciphertext, Base64.DEFAULT)); //byte[]
  String result = new String(decrypted);
  Log.i("Decrypted Data",result);