I have a Java program that can encrypt using AES/ECB/PKCS5Padding
cipher with 256bit key, and I want to write a PHP script that produce the same result.
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.
Could someone point out what's wrong in the PHP script ?
Thanks.
Here are the example codes, you can simply run it after copy & paste:
Java
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"));
}
}
PHP
<?php
class PHPCipher {
private $key;
public function __construct($key)
{
$this->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->key, $iv);
$result = mcrypt_generic($td, $this->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->encrypt('abcdefg');