[英]openssl_encrypt, openssl_decrypt key, iv
根据OpenSSL
( https://www.openssl.org/docs/apps/enc.html#OPTIONS )的文档,他们希望key
和iv
的hex-digit
数值; 这只意味着数字吗? 或者md5
哈希会吗? (因为md5
似乎不可逆)
key
和iv
因为PHP
函数openssl_encrypt
中的$password
实际上是关键。 (几乎)直接来自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函数。 你很难在终端中抛出二进制数据,因此为什么密钥必须是十六进制编码的。
但是在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
如果您需要的只是完成工作 - 使用流行的加密库,不要自己编写。
我花了一些时间来处理openssl文档 。 最后,我得到了使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.