How do I make AES 256-bit, ECB mode, PKCS5 Padding encryption works between Java and PHP?
<p>I have a Java program that can encrypt using <code>AES/ECB/PKCS5Padding</code> cipher with 256bit key, and I want to write a PHP script that produce the same result. </p>

<p>However, my script failed to do so. I kind of get a feel that how they process the key before encryption is the problem, but I cannot tell.</p>

<p>Could someone point out what's wrong in the PHP script ?</p>

<p>Thanks.</p>

<p>Here are the example codes, you can simply run it after copy &amp; paste:</p>

<p><strong>Java</strong> </p>

<pre><code>import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;

public class JavaCipher {

    private SecretKeySpec secretKey;

    private JavaCipher(String secret) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte[] digest = sha.digest(secret.getBytes("UTF-8"));
        secretKey = new SecretKeySpec(digest, "AES");
    }

    private String encrypt(String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        return DatatypeConverter.printHexBinary(encrypted).toLowerCase();
    }

    public static void main(String[] args) throws Exception {  
        JavaCipher cipher = new JavaCipher("some random key");

        // print d013acccb5d191a00898ac87057383ff
        System.out.println(cipher.encrypt("abcdefg"));
    }
}
</code></pre>

<p><strong>PHP</strong></p>

<pre><code>&lt;?php

class PHPCipher {

    private $key;

    public function __construct($key)
    {
        $this-&gt;key = substr(hash('sha256', $key), 0, 32);
    }

    public function encrypt($data)
    {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $this-&gt;key, $iv);
        $result = mcrypt_generic($td, $this-&gt;pad($data, $size));
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return bin2hex($result);
    }

    private function pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
}

$cipher = new PHPCipher('some random key');
// print 9a4df66d67a3e8d4a1dda7cda6e94d07
echo $cipher-&gt;encrypt('abcdefg');
</code></pre>