PHP Conference Japan 2024

openssl_pkcs7_decrypt

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

openssl_pkcs7_decrypt解密 S/MIME 加密訊息

說明

openssl_pkcs7_decrypt(
    字串 $input_filename,
    字串 $output_filename,
    #[\SensitiveParameter] OpenSSLCertificate|字串 $certificate,
    #[SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|陣列|字串|null $private_key = null
): 布林值

使用由 certificateprivate_key 指定的憑證及其關聯的私鑰,解密 input_filename 指定檔案中包含的 S/MIME 加密訊息。

參數

input_filename

output_filename

解密後的訊息會寫入 output_filename 指定的檔案中。

certificate

private_key

返回值

成功時返回 true,失敗時返回 false

更新日誌

版本 說明
8.0.0 private_key 現在接受 OpenSSLAsymmetricKeyOpenSSLCertificate 實例;先前接受類型為 OpenSSL keyOpenSSL 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
"解密失敗!";
}
?>

新增註釋

使用者貢獻的註釋 1 則註釋

oliver at anonsphere dot com
13 年前
如果您要解密收到的電子郵件,請記住,您需要完整的加密訊息,包括 MIME 標頭。

<?php

// 取得完整訊息
$encrypted = imap_fetchmime($stream, $msg_number, "1", FT_UID);
$encrypted .= imap_fetchbody($stream, $msg_number, "1", FT_UID);

// 寫入所需的暫存檔案
$infile = tempnam("", "enc");
file_put_contents($infile, $encrypted);
$outfile = tempnam("", "dec");

// 憑證相關設定
$public = file_get_contents("/path/to/your/cert.pem");
$private = array(file_get_contents("/path/to/your/cert.pem"), "password");

// 準備好了嗎?開始!
if(openssl_pkcs7_decrypt($infile, $outfile, $public, $private))
{
// 解密成功
echo file_get_contents($outfile);
}
else
{
// 解密失敗
echo "糟糕!解密失敗!";
}

// 移除暫存檔案
@unlink($infile);
@
unlink($outfile);

?>
To Top