0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPのopenssl_encrypt関数で暗号化したものをopensslコマンドで複合化

Last updated at Posted at 2021-01-18

PHPのopenssl_encryptとopenssl

phpのopenssl_encrypt()で暗号化した文字列をopensslコマンドで複合化しないといけない案件があったのでメモ

エンコード条件

ivを指定してエンコードするのが定石だが、今回はivの指定がなかった。

$enc_key = "abcedfg";
$enc_method = "aes-256-cbc";
$text = "some encode text";

openssl_encrypt($text, $enc_method, $enc_key);

opensslで復号

openssl_encrypt()はIVの指定をしていない場合、key文字列と同じものが指定されるもよう

ポイント

  • key文字列を16進数にしたものを-Kオプションに指定する
  • ivは-Kオプションに指定した文字の先頭数文字が対応するみたい(文字数はmethod依存?)
/**
 * 文字列を16進数に変換
 * @param $x
 * @return string
 */
function strtohex($x)
{
    $s='';
    foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
    return($s);
}


$key = strtohex($enc_key);
$iv = substr($key, 0, 32);  //$keyの先頭32文字で複合化できた

$cmd = sprintf('echo -n "%s" | openssl enc -d -%s -base64 -A -K %s -iv %s',
  $custom_data, $key, $iv, $iv);

exec($cmd, $out);
echo $out;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?