简体   繁体   中英

AES-128 Encryption with Base64 Encoding doesn't act the same in Java and PHP with longer strings

I have been trying to get Encryption/Decryption to work the same in Java (Android) and PHP and produce the same results for client/server communications.

I'm using the code below for encryption, but I don't know what's wrong with it. Running both with the same key and small strings produce the same encrypted value, with longer strings however, I get two different results. PHP:

$str = 'test1234test1234';

$key = 'TESTKEYTESTKEY12';

$block = mcrypt_get_block_size('des', 'ecb');

$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB));

and in Java ( on Android ):

public static String encryptTest() {
  String cleartext = "test1234test1234";
  String key = "TESTKEYTESTKEY12";
    byte[] raw = key.getBytes();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    try {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted;
        encrypted = cipher.doFinal(cleartext.getBytes());
    return new String(Base64.encode(encrypted,Base64.DEFAULT));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Running this with String test1234 gives: 8i4KEe82TQl0Zdlc14fwAg== in both implementations. With string test1234test1234 however I get 4s5a0edsvwWt/3/enRe0wgJQD/0zL45NRb/r3p6L/Is= with PHP, and 4s5a0edsvwWt/3/enRe0wgA0jk78zwWJr1xsosZbYUA= with Java. I'm not sure what's wrong and I'm not knowledgeable enough about Cryptography.

The main problem of your Java code is that you don't specify the cipher mode and the used padding algorithm. Therefore which cipher mode and padding algorithm is used depends on the used crypto provider and in this specific detail Android works different to J2SE.

If I execute your Java code on J2SE I get the same result as you got with PHP. This does not change if I change the code to use Cipher.getInstance("AES/ECB/PKCS5Padding"); .

As only the last block of your cipher text changes I assume that Android uses a different padding algorithm by default.

The fact you have different results for short versus long strings suggest you are using different padding on each implementation.

Make sure you use the same type of padding on both your java and your php implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM