1

I'm trying to send encrypted data from my android app to a PHP scripts that decrypts the data.

In android I use the following encryption method:

public String encryptAES(String key, String mdp) throws NoSuchPaddingException, NoSuchAlgorithmException {
    byte[] skey = key.getBytes();
    byte[] pwd = mdp.getBytes();
    byte[] encrypted = null;
    SecretKeySpec secretKeySpec = new SecretKeySpec(skey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    try {
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    try {
        encrypted = cipher.doFinal(pwd);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        e.printStackTrace();
    }
    return Arrays.toString(Base64.encode(encrypted, Base64.DEFAULT));
}

and I use this to decrypt in PHP:

$data = mcrypt_decrypt(MCRYPT_RIJNADEAL_128, $key, $cipherText, MCRYPT_MODE_ECB);

The problem is that it doesn't decrypt to the wanted plain text in PHP.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
ryuzakinho
  • 1,891
  • 3
  • 21
  • 35

1 Answers1

0

Arrays#toString() returns an array representation with [, ] and commas. You can directly get a Base 64 encoded string through the Base64 class:

return Base64.encodeToString(encrypted, Base64.DEFAULT);

In PHP you need to decode the ciphertext before use

$cipherText = base64_decode($cipherText);

To make sure you use the same mode of operation, you need to provide a full cipher string (providers may have different defaults, so you need to specify it yourself to prevent problems):

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

And use the same padding (PKCS#5/PKCS#7 padding is the same) in PHP (only provides ZeroPadding). This answer provides drop in code for that.


Further security considerations

Don't use ECB mode. It is very insecure. Use at the very least CBC mode with a random IV. The IV doesn't have to be secret, so you can simply prepend it to the ciphertext before you encode and send it. The IV can be sliced off before decryption and used for decryption.

To make it even more secure, you should authenticate your ciphertexts. This can be with an authenticated mode like GCM or with an encrypt-then-MAC scheme with a strong MAC like HMAC-SHA256.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222