Here is how AES encryption works between Java and PHP using the mcrypt module in PHP.
This is mainly a quick summary of the 4-part tutorial at: http://propaso.com/blog/?cat=6
Generate Key in Java
01 |
String iv = "fedcba9876543210"; |
02 |
IvParameterSpec ivspec; |
06 |
ivspec = new IvParameterSpec(iv.getBytes()); |
08 |
keygen = KeyGenerator.getInstance("AES"); |
10 |
key = keygen.generateKey(); |
12 |
keyspec = new SecretKeySpec(key.getEncoded(), "AES"); |
Encryption in Java
4 |
cipher = Cipher.getInstance("AES/CBC/NoPadding"); |
5 |
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); |
6 |
encrypted = cipher.doFinal(padString(text).getBytes()); |
Decryption in Java
4 |
cipher = Cipher.getInstance("AES/CBC/NoPadding"); |
5 |
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); |
6 |
decrypted = cipher.doFinal(hexToBytes(code)); |
Encryption in PHP
01 |
function encrypt($str, $key) { |
02 |
$key = $this->hex2bin($key); |
04 |
$td = mcrypt_module_open("rijndael-128", "", "cbc","fedcba9876543210"); |
06 |
mcrypt_generic_init($td, $key, CIPHER_IV); |
07 |
$encrypted = mcrypt_generic($td, $str); |
09 |
mcrypt_generic_deinit($td); |
10 |
mcrypt_module_close($td); |
12 |
return bin2hex($encrypted); |
Decryption in PHP
01 |
function decrypt($code, $key) { |
02 |
$key = $this->hex2bin($key); |
03 |
$code = $this->hex2bin($code); |
05 |
$td = mcrypt_module_open("rijndael-128", "", "cbc","fedcba9876543210"); |
07 |
mcrypt_generic_init($td, $key, CIPHER_IV); |
08 |
$decrypted = mdecrypt_generic($td, $code); |
10 |
mcrypt_generic_deinit($td); |
11 |
mcrypt_module_close($td); |
13 |
return utf8_encode(trim($decrypted)); |
Additional functions in Java
01 |
private byte[] hexToBytes(String hex) { |
02 |
String HEXINDEX = "0123456789abcdef"; |
03 |
int l = hex.length() / 2; |
04 |
byte data[] = new byte[l]; |
07 |
for (int i = 0; i < l; i++) { |
08 |
char c = hex.charAt(j++); |
11 |
n = HEXINDEX.indexOf(c); |
14 |
n = HEXINDEX.indexOf(c); |
22 |
private String padString(String source) { |
23 |
char paddingChar = ' '; |
25 |
int padLength = size - source.length() % size; |
27 |
for (int i = 0; i < padLength; i++) { |
28 |
source += paddingChar; |
Additional functions in PHP
1 |
function hex2bin($hexdata) { |
4 |
for ($i = 0; $i < strlen($hexdata); $i += 2) { |
5 |
$bindata .= chr(hexdec(substr($hexdata, $i, 2))); |