openssl_encrypt,openssl_decrypt key,iv

问题描述 投票:3回答:2

根据OpenSSLhttps://www.openssl.org/docs/apps/enc.html#OPTIONS)的文献,他们期望hex-digitkeyiv值;这只意味着数字吗?或者md5哈希会做什么? (因为md5似乎不可逆)

  • 请注意我提到keyiv,因为$password函数PHP中的openssl_encrypt实际上是关键。

(几乎)直接来自PHP评论(http://php.net/manual/en/function.openssl-encrypt.php

function strtohex($x) 
{
    $s='';
    foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
    return($s);
} 

$source = 'It works !';

$iv = substr( md5( "123sdfsdf4567812345678" ), 0, 16 );
$pass = '1234567812345678';
$method = 'aes-256-cbc';

echo "\niv in hex to use: ".$iv;
echo "\nkey in hex to use: ".strtohex($pass);
echo "\n";

file_put_contents ('./file.encrypted',openssl_encrypt ($source, $method, $pass, true, $iv));

$exec = "openssl enc -".$method." -d -in file.encrypted -nosalt -nopad -K ".strtohex($pass)." -iv ".$iv;

echo 'executing: '.$exec."\n\n";
echo exec ($exec);
echo "\n";
php encryption openssl php-openssl
2个回答
3
投票

您的第一个链接是关于命令行工具,而不是PHP函数。你很难在终端中抛出二进制数据,因此为什么密钥必须是十六进制编码的。

然而,在PHP中,openssl_encrypt()openssl_decrypt()期望一个原始的二进制字符串。

该文档也具有误导性,因为它提到了“密码”而不是“密钥”。您已经注意到了,但是加密密钥不是您应该通过键盘输入的内容而且md5()-ing任何东西也不是加密密钥的答案。密钥必须通过openssl_random_pseudo_bytes()随机生成(或者至少对你的情况来说是最方便的方式):

$key = openssl_random_pseudo_bytes(32);

(同样适用于IVs)

如果您需要对生成的$key进行十六进制编码,只需将其传递给bin2hex(),但您提供的示例有点破碎......您正在进行双重加密。通过PHP加密文件内容就足够了,您不需要处理命令行。

请注意,我的答案远非关于加密的整个故事。您还应该添加身份验证,正确填充,仔细考虑如何管理和存储密钥等。

如果你想了解它,这里有一个相当简短但仍然描述性的博客文章,为你应该涵盖的关键点提供正确的答案:http://timoh6.github.io/2014/06/16/PHP-data-encryption-cheatsheet.html

如果您需要的只是完成工作 - 使用流行的加密库,不要自己编写。


0
投票

我花了一些时间与openssl documentation合作。最后,我得到了使用base64_encode()返回编码和解码为ASCII文本的解决方案:

//Return encrypted string
public function stringEncrypt ($plainText, $cryptKey = '7R7zX2Urc7qvjhkr') {

  $length   = 8;
  $cstrong  = true;
  $cipher   = 'aes-128-cbc';

  if (in_array($cipher, openssl_get_cipher_methods()))
  {
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext_raw = openssl_encrypt(
      $plainText, $cipher, $cryptKey, $options=OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext_raw, $cryptKey, $as_binary=true);
    $encodedText = base64_encode( $iv.$hmac.$ciphertext_raw );
  }

  return $encodedText;
}


//Return decrypted string
public function stringDecrypt ($encodedText, $cryptKey = '7R7zX2Urc7qvjhkr') {

  $c = base64_decode($encodedText);
  $cipher   = 'aes-128-cbc';

  if (in_array($cipher, openssl_get_cipher_methods()))
  {
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = substr($c, 0, $ivlen);
    $hmac = substr($c, $ivlen, $sha2len=32);
    $ivlenSha2len = $ivlen+$sha2len;
    $ciphertext_raw = substr($c, $ivlen+$sha2len);
    $plainText = openssl_decrypt(
      $ciphertext_raw, $cipher, $cryptKey, $options=OPENSSL_RAW_DATA, $iv);
  }

  return $plainText;
}
© www.soinside.com 2019 - 2024. All rights reserved.