2024 日本 PHP 研討會

openssl_cms_encrypt

(PHP 8)

openssl_cms_encrypt加密 CMS 訊息

說明

openssl_cms_encrypt(
    字串 $input_filename,
    字串 $output_filename,
    OpenSSLCertificate|陣列|字串 $certificate,
    ?陣列 $headers,
    整數 $flags = 0,
    整數 $encoding = OPENSSL_ENCODING_SMIME,
    int $cipher_algo = OPENSSL_CIPHER_AES_128_CBC
): bool

此函數會根據傳入的憑證將內容加密給一個或多個收件者。

參數

input_filename

要加密的檔案。

output_filename

輸出檔案。

certificate

要加密的收件者。

headers

使用 S/MIME 時要包含的標頭。

flags

要傳遞給 CMS_sign 的旗標。

encoding

要輸出的編碼。其中之一:OPENSSL_ENCODING_SMIMEOPENSSL_ENCODING_DEROPENSSL_ENCODING_PEM

cipher_algo

要使用的加密演算法。

返回值

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

更新日誌

版本 說明
8.1.0 預設的加密演算法 (cipher_algo) 現在是 AES-128-CBC (OPENSSL_CIPHER_AES_128_CBC)。先前使用的是 PKCS7/CMS (OPENSSL_CIPHER_RC2_40)。
新增註解

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

Sebastian
3 年前
我花了一段時間才找到使用這些函數來簽署和加密資料的正確方法。
我需要這個功能來與德國健康保險提供商溝通,作為 DiGA 的一部分。也許有人會覺得這很有用。

<?php
函式 signAndEncrypt(字串 $rawData): 字串
{
$tempDir = __DIR__ . '/tmp';
$tempfileOriginal = tempnam($tempDir, 'original');
$tempfileSigned = tempnam($tempDir, 'signed');
$tempfileEncrypted = tempnam($tempDir, 'signedEncrypted');

file_put_contents($tempfileOriginal, $rawData);

// 選擇收件人對應的正確憑證
$recipientsCertificateFile = __DIR__ . '/recipientsCertificate.pem';
// -----BEGIN CERTIFICATE----- ...-----END CERTIFICATE-----
$recipientsCertificate = file_get_contents($recipientsCertificateFile);

// 憑證:
// 資料:
// 版本: 3 (0x2)...
$myCertificate = file_get_contents(__DIR__ . '/my.crt');
$myPrivateKey = openssl_pkey_get_private(
// -----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----
file_get_contents(__DIR__ . '/my.prv.key.pem')
);

openssl_cms_sign(
input_filename: $tempfileOriginal,
output_filename: $tempfileSigned,
certificate: $myCertificate,
private_key: $myPrivateKey,
headers: [],
encoding: OPENSSL_ENCODING_DER,
);

openssl_cms_encrypt(
input_filename: $tempfileSigned,
output_filename: $tempfileEncrypted,
certificate: $recipientsCertificate,
headers: [],
flags: OPENSSL_CMS_BINARY | OPENSSL_CMS_NOSIGS | OPENSSL_CMS_NOVERIFY,
encoding: OPENSSL_ENCODING_DER,
cipher_algo: OPENSSL_CIPHER_AES_256_CBC
);
return file_get_contents($tempfileEncrypted);
}
To Top