CakeFest 2024: The Official CakePHP Conference

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_decryptS/MIME 暗号化されたメッセージを復号する

説明

openssl_pkcs7_decrypt(
    string $input_filename,
    string $output_filename,
    OpenSSLCertificate|string $certificate,
    OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null $private_key = null
): bool

input_filename で指定したファイル中の S/MIME 暗号化されたメッセージを、 certificateprivate_key で 指定した証明書とそれに関連付けられた秘密鍵を用いて復号します。

パラメータ

input_filename

output_filename

復号したメッセージは、output_filename で指定したファイルに出力されます。

certificate

private_key

戻り値

成功した場合に true を、失敗した場合に false を返します。

変更履歴

バージョン 説明
8.0.0 private_key は、 OpenSSLAsymmetricKey または OpenSSLCertificate クラスのインスタンスを受け入れるようになりました。 これより前のバージョンでは、 OpenSSL key または OpenSSL X.509 CSR 型のリソースを受け入れていました。

例1 openssl_pkcs7_decrypt() の例

<?php
// $cert および $key にはあなたの個人証明書と秘密鍵が含まれており、
// あなたはS/MIMEメッセージの受信者であると仮定します。
$infilename = "encrypted.msg"; // 暗号化されたメッセージを含むファイル
$outfilename = "decrypted.msg"; // このファイルへの書き込み権限が必要

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key)) {
echo
"復号しました!";
} else {
echo
"復号に失敗しました!";
}
?>

add a note

User Contributed Notes 1 note

up
1
oliver at anonsphere dot com
12 years ago
If you want to decrypt a received email, keep in mind that you need the full encrypted message including the mime header.

<?php

// Get the full message
$encrypted = imap_fetchmime($stream, $msg_number, "1", FT_UID);
$encrypted .= imap_fetchbody($stream, $msg_number, "1", FT_UID);

// Write the needed temporary files
$infile = tempnam("", "enc");
file_put_contents($infile, $encrypted);
$outfile = tempnam("", "dec");

// The certification stuff
$public = file_get_contents("/path/to/your/cert.pem");
$private = array(file_get_contents("/path/to/your/cert.pem"), "password");

// Ready? Go!
if(openssl_pkcs7_decrypt($infile, $outfile, $public, $private))
{
// Decryption successful
echo file_get_contents($outfile);
}
else
{
// Decryption failed
echo "Oh oh! Decryption failed!";
}

// Remove the temp files
@unlink($infile);
@
unlink($outfile);

?>
To Top