略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: openssl_cms_decrypt

2024-12-22

openssl_cms_decrypt

(PHP 8)

openssl_cms_decryptDecrypt a CMS message

说明

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

Decrypts a CMS message.

参数

input_filename

The name of a file containing encrypted content.

output_filename

The name of the file to deposit the decrypted content.

certificate

The name of the file containing a certificate of the recipient.

private_key

The name of the file containing a PKCS#8 key.

encoding

The encoding of the input file. One of OPENSSL_ENCODING_SMIME, OPENSSL_ENCODING_DER or OPENSSL_ENCODING_PEM.

返回值

成功时返回 true, 或者在失败时返回 false

add a noteadd a note

User Contributed Notes 1 note

up
1
Sebastian
1 year 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);
}

官方地址:https://www.php.net/manual/en/function.openssl-cms-decrypt.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3