总有人间一两风,填我十万八千梦

PHP openssl_cms_encrypt 用法 手册 | 示例代码

PHP开发手册 归档 401℃ 0评论

openssl_cms_encrypt

(PHP 8)

openssl_cms_encryptEncrypt a CMS message

说明

openssl_cms_encrypt(
    string $input_filename,
    string $output_filename,
    OpenSSLCertificate array string $certificate,
    array null $headers,
    int $flags = 0,
    int $encoding = OPENSSL_ENCODING_SMIME,
    int $cipher_algo = OPENSSL_CIPHER_RC2_40
): bool

This function encrypts content to one or more recipients, based on the certificates that are passed to it.

参数

input_filename

The file to be encrypted.

output_filename

The output file.

certificate

Recipients to encrypt to.

headers

Headers to include when S/MIME is used.

flags

Flags to be passed to CMS_sign.

encoding

An encoding to output. One of OPENSSL_CMS_SMIME, OPENSLL_CMS_DER or OPENSSL_CMS_PEM.

cipher_algo

A cypher to use.

返回值

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

用户贡献的笔记

Sebastian

It took me a while to find out the correct way how to sign and encrypt 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 signAndEncrypt(string $rawData): string
{
   
$tempDir = __DIR__ . '/tmp';
   
$tempfileOriginal = tempnam($tempDir, 'original');
   
$tempfileSigned = tempnam($tempDir, 'signed');
   
$tempfileEncrypted = tempnam($tempDir, 'signedEncrypted');

    file_put_contents($tempfileOriginal, $rawData);

    // pick the correct certificate for the recipient
   
$recipientsCertificateFile = __DIR__ . '/recipientsCertificate.pem';
   
// -----BEGIN CERTIFICATE----- ...-----END CERTIFICATE-----
   
$recipientsCertificate = file_get_contents($recipientsCertificateFile);

    // 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_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);
}

转载请注明:悠然品鉴 » PHP openssl_cms_encrypt 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址