PHP Velho Oeste 2024

openssl_cms_decrypt

(PHP 8)

openssl_cms_decryptCMS メッセージを復号化する

説明

openssl_cms_decrypt(
    string $input_filename,
    string $output_filename,
    OpenSSLCertificate|string $certificate,
    OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null $private_key = null,
    int $encoding = OPENSSL_ENCODING_SMIME
): bool

CMS メッセージを復号化します。

パラメータ

input_filename

暗号化された内容を含むファイル名。

output_filename

復号化した内容を書き込むファイル名。

certificate

メッセージの受け手の証明書のファイル名。

private_key

PKCS#8 形式の鍵を含むファイル名。

encoding

入力ファイルのエンコーディング。 OPENSSL_ENCODING_SMIME, OPENSSL_ENCODING_DER, OPENSSL_ENCODING_PEM のいずれかです。

戻り値

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

add a note add a note

User Contributed Notes 1 note

up
3
Sebastian
3 years ago
It took me a while to find out the correct way how to decrypt and verify data with these functions.
I needed that to communicate with German Health Insurance Providers as part of a DiGA. Maybe someone finds that useful.

<?php
function decryptAndVerify($signedAndEncryptedRawData): string
{
   
$tempDir = __DIR__ . '/tmp';
   
$originalFile = tempnam($tempDir, 'original');
   
$decryptedFile = tempnam($tempDir, 'decrypted');
   
$verifiedFile = tempnam($tempDir, 'verified');

   
file_put_contents($originalFile, $signedAndEncryptedRawData);
   
   
// One file with all possible certificates one after the other
    // -----BEGIN CERTIFICATE----- ...-----END CERTIFICATE-----
   
$allPossibleSenderCertificates = __DIR__ . '/untrusted.pem';

   
// Certificate:
    //    Data:
    //        Version: 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_decrypt(
       
input_filename: $originalFile,
       
output_filename: $decryptedFile,
       
certificate: $myCertificate,
       
private_key: $myPrivateKey,
       
encoding: OPENSSL_ENCODING_DER
   
);

   
openssl_cms_verify(
       
input_filename: $decryptedFile,
       
flags: OPENSSL_CMS_BINARY | OPENSSL_CMS_NOSIGS | OPENSSL_CMS_NOVERIFY,
       
ca_info: [],
       
untrusted_certificates_filename: $allPossibleSenderCertificates,
       
content: $verifiedFile,
       
encoding: OPENSSL_ENCODING_DER
   
);
    return
file_get_contents($verifiedFile);
}
To Top