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);
$allPossibleSenderCertificates = __DIR__ . '/untrusted.pem';
$myCertificate = file_get_contents(__DIR__ . '/my.crt');
$myPrivateKey = openssl_pkey_get_private(
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);
}