Java – Encrypts/decrypts strings between Java and PHP

Encrypts/decrypts strings between Java and PHP… here is a solution to the problem.

Encrypts/decrypts strings between Java and PHP

I’m using AES encryption to encrypt and decrypt strings between the server-side php and Android applications (as clients).

The encrypted string in PHP is:

HaxRKnMxT24kCJWUXaVvqDHahzurJQK+sYA4lIHql/U=

In Java it is:

HaxRKnMxT24kCJWUXaVvqD/KMEkJTPTXEcCsHIYGX9TGtCNOHQcJyUURPk8qlgf3

I use phpseclib for encryption in PHP scripts.

What am I missing here?

Here is the relevant Java code

SecretKeySpec skeySpec = new SecretKeySpec(pad16(pass), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] out = c.doFinal( input )

Here is the PHP code:

$aes = new Crypt_AES();
$aes->setKey('password');
$encrypted_encoded_text =  base64_encode($aes->encrypt($plaintext));

Solution

For encryption/decryption to work in different languages, few things need to be the same.

  1. Encryption algorithm (duh!)
  2. The key (uh, again!)
  3. Key size
  4. Mode of operation (ECB, CBC, CTR).
  5. Initialize the vector (ECB is not required if it is a CBC).
  6. Fill scheme

    There may be more factors….

Are you sure that all of this is the same in both languages? If yes, then your encryption/decryption should work perfectly, unless there is a bug in the implementation (which is very rare but possible).

Related Problems and Solutions