PHP的mcrypt_encrypt和openssl命令行输出不同的密码

问题描述:

I am new to encryption. I want to encode a string with AES 128bit encryption. I can do this in PHP:

$key = 'Hello';
$plain = 'Hello Hello Hello Hello';

$cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plain, MCRYPT_MODE_CBC);

echo base64_encode($cipher);

This outputs:

bzXdTNochlsQwpR9hzSSS6ihG+MYIZIDZZlF85pIXlQ=

I tried the same with openssl command line:

openssl enc -aes-128-cbc -a -nosalt -in plain.txt -out encrypted.enc -pass pass:Hello

And the string saved in encrypted.enc is:

5apwiN8MdAuJ9nEW82XMyR0H3VKpI/vWc7xV2iVjCTE=

Why is it different?

The reason why I am trying to get the same output with both PHP and command line openssl is because I will have two separate web services communicating together. One service will have PHP available so I can use that but the other one will not be using PHP so I will probably have to use openssl in command line.

我是加密新手。 我想用AES 128位加密编码一个字符串。 我可以在PHP中执行此操作: p>

  $ key ='Hello'; 
 $ plain ='Hello Hello Hello Hello'; 
 
 $ cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128  ,$ key,$ plain,MCRYPT_MODE_CBC); 
 
echo base64_encode($ cipher); 
  code>  pre> 
 
 

输出: p>

  bzXdTNochlsQwpR9hzSSS6ihG + MYIZIDZZlF85pIXlQ = 
  code>  pre> 
 
 

我尝试使用openssl命令行: p>

  openssl enc  -aes-128-cbc -a -naltalt -in plain.txt -out encrypted.enc -pass pass:Hello 
  code>  pre> 
 
 

并且字符串保存在encrypted.enc中 是: p>

  5apwiN8MdAuJ9nEW82XMyR0H3VKpI / vWc7xV2iVjCTE = 
  code>  pre> 
 
 

为什么它不同? p>

我试图用PHP和命令行openssl获得相同输出的原因是因为我将有两个单独的Web服务一起通信。 一个服务将提供PHP,所以我可以使用它,但另一个服务不会使用PHP,所以我可能不得不在命令行中使用openssl。 p> div>

You mixed up password and key. Add a -p to your openssl command line to see the actual key used and observe http://php.net/manual/en/function.mcrypt-encrypt.php string mcrypt_encrypt ( string $cipher , string $key <= key! Not password.

Edit:

You also have problems with padding. Now making your plain text 48 chars (3*128 bit=3*16 bytes) long:

$plain = 'Hello Hello Hello Hellox';
$plain .= $plain;
function hexstr($hexstr) {
  // return pack('H*', $hexstr); also works but it's much harder to understand.
  $return = '';
  for ($i = 0; $i < strlen($hexstr); $i+=2) {
    $return .= chr(hexdec($hexstr[$i] . $hexstr[$i+1]));
  }
  return $return;
}
$cipher = @mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hexstr('25c506a9e4a0b3100d2d86b49b83cf9a'), $plain, MCRYPT_MODE_CBC, hexstr('00000000000000000000000000000000'));

echo base64_encode($cipher);
echo "
";

And

openssl enc -aes-128-cbc -a -iv 0  -nosalt -in plain.txt  -K 25c506a9e4a0b3100d2d86b49b83cf9a -nopad

results the same:

EZjBup0sfRAkIZ2/IQ3bKHWXHG4qBVv4uyW0PnxJJWvWHanNgE1QyBHMpWoZqejR