php - 如何使用 PHP openssl 命令(DER 格式?)获得相同的输出 SMIME 签名

标签 php openssl

我一直在尝试使用 PHP 的内置 openssl 函数复制此命令,但没有成功。我试过 openssl_pkcs7_sign 和 openssl_pkcs7_encrypt 的变体。我认为问题在于没有标志指示 DER 格式输出。

这是我要复制的 openssl 命令:

openssl smime -sign -signer mycert.pem -certfile mybundle.crt -inkey mykey.pem -nodetach -outform der -in file_in -out file_out

最佳答案

openssl_pkcs7_sign 确实以 PEM 格式对数据进行签名,但您可以只获取 PEM 数据的 base64 block 并使用 base64_decode() 将其转换为 DER。

function get_base64($file_name) {
   $content = file($file_name, FILE_IGNORE_NEW_LINES);
   $base64_data = "";
   for ($i=5; $i<sizeof($content); $i++){ // take only the base64 chunk
        $base64_data .=  $content[$i];
   }
   return $base64_data;
}

function pem2der($base64_data) {
   $der = base64_decode($base64_data);
   return $der;
}

if (openssl_pkcs7_sign(           // Signs file_in and saves as file_out in PEM format
    "file_in",                    // Input file
    "file_out",                   // Output file (PEM format)
    "file://../.pki/company.crt", // Certificate (mycert.pem)
    "file://../.pki/company.key", // Private key (mykey.pem)
    array(),
    PKCS7_NOATTR,
    "../.pki/company.cacrt"       // Intermediate certificate (mybundle.crt)
    )) {
    $data = pem2der(get_base64("file_out"));  // converts content of file_out to DER format
    $out = fopen("file_out", "w") or die("Unable to open file!");
    fwrite($out,$data);           // output file (DER format)
    fclose($out);
    echo("File signed successfully!")
}
?>

关于php - 如何使用 PHP openssl 命令(DER 格式?)获得相同的输出 SMIME 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694111/

相关文章:

php ob_flush : How do I make the browser window/page scroll down with the output?

php - mysql_data_seek 不工作

ssl - 推荐的 OpenSSL 和密码学学习资源有哪些?

c++ - SSL 握手错误 : session id context uninitialized

c++ - 使用没有证书的 SSL

c++ - 如何从 unsigned char * 模数和指数 65537(RSA_F4) 创建 RSA 公钥

php - Google Search Console API 多个维度

php - 用MySQL和PHP读取部分json数据

php - 根据变量值隐藏和显示 div

c - 如何通知服务器客户端正在关闭连接