Miscellaneous AES128 with zero encryption obtained from php and java

I have a different result between java and php method when running AES128 with zero padding and no IV encryption.

Here's the php code:

<?php
$ptaDataString = "secretdata";
$ptaDataString = encryptData($ptaDataString);
$ptaDataString = base64_encode($ptaDataString);
function encryptData($input) {
                $ptaKey = 'secret'; 
                $iv = "\0";
                $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $ptaKey, $input, MCRYPT_MODE_CBC, $iv);
                return $encrypted;
}
echo $ptaDataString;
?>

And here is the Java code:

public static String encrypt() throws Exception {
    try {
        String data = "secretdata";
        String key = "secret0000000000";
        String iv = "0000000000000000";

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        int blockSize = cipher.getBlockSize();

        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);

        return new sun.misc.BASE64Encoder().encode(encrypted);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

php: kjgE5p / 3qrum6ghdjiVIoA ==

Java result: zLKhVMksRRr1VHQigmPQ2Q ==

Any help would be appreciated, Thanks

+4
source share
1 answer

In Java, the null byte, expressed as a string, is "\0"not "0". If you correct your example as follows, the results will match:

String data = "secretdata";
String key = "secret\0\0\0\0\0\0\0\0\0\0";
String iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

In the case of IV, it is probably easier to write:

byte[] iv = new byte[<block size>];

sun.misc.BASE64Encoder(). -, sun.*, , . :

return DatatypeConverter.printBase64Binary(encrypted);
+3

All Articles