PHP中的等效AES 128位

时间:2012-02-27 09:03:40

标签: java php encryption aes

我在Java中有这段代码,它使用AES 128位将源String加密为Base64加密值。但是我找不到类似的PHP函数产生相同的结果。任何帮助将不胜感激

    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)));

2 个答案:

答案 0 :(得分:6)

这就是答案。在他提到的帖子中,@ laststead和原始答案的所有者信用

<?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);
}
?>

答案 1 :(得分:0)

我对将Java代码翻译成PHP的要求略有不同。

Java代码:

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等价物:

$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;
}