romy_ngo
romy_ngo

Reputation: 1061

Equivalent AES 128 bit in PHP

I have this piece of code in Java, which encrypts a source String to a Base64 encrypted value using AES 128 bit. However I failed to find similar PHP function producing the same result. Any help would be greatly appreciated

    String key = "1234567890123456";
    String source = "The quick brown fox jumped over the lazy dog";

    byte[] raw = key.getBytes();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

    // Instantiate the cipher
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    byte[] encrypted = cipher.doFinal(source.getBytes());
    System.out.println(new String(Base64.encodeBase64(encrypted)));

Upvotes: 2

Views: 10259

Answers (2)

SenG
SenG

Reputation: 731

I had a slightly different requirement of translating the Java code to PHP.

Java Code:

SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key
           .toCharArray()), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());              
return new String(Hex.encodeHex(encrypted));

PHP equivalent:

$storeServerToken = 'my_token';
date_default_timezone_set('UTC');
$str = $storeServerToken . '|' . date('Y-m-d H:i:s', gmmktime());
$key = 'my_key';
return bin2hex($this->_encrypt($str, $this->_hex2bin($key)));

private function _encrypt($str, $key) {
    $block = mcrypt_get_block_size('rijndael_128', 'ecb');
    $pad = $block - (strlen($str) % $block);
    $str .= str_repeat(chr($pad), $pad);
    return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
}

private function _hex2bin($hexstr) {
    $n = strlen($hexstr);
    $sbin = "";
    $i = 0;
    while ($i < $n) {
        $a = substr($hexstr, $i, 2);
        $c = pack("H*", $a);
        if ($i == 0) {
            $sbin = $c;
        } else {
            $sbin.=$c;
        }
        $i+=2;
    }

    return $sbin;
}

Upvotes: 0

romy_ngo
romy_ngo

Reputation: 1061

This is the answer. Credit goes to @owlstead and the owner of the original answer in the thread that he mentioned

<?php
function encrypt($str, $key){
     $block = mcrypt_get_block_size('rijndael_128', 'ecb');
     $pad = $block - (strlen($str) % $block);
     $str .= str_repeat(chr($pad), $pad);
     return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB));
}

function decrypt($str, $key){ 
     $str = base64_decode($str);
     $str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
     $block = mcrypt_get_block_size('rijndael_128', 'ecb');
     $pad = ord($str[($len = strlen($str)) - 1]);
     $len = strlen($str);
     $pad = ord($str[$len-1]);
     return substr($str, 0, strlen($str) - $pad);
}
?>

Upvotes: 6

Related Questions