Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the same output SMIME signing using PHP openssl commands (DER Format?)

Tags:

php

openssl

I've been trying to duplicate this command using PHP's built in openssl functions with no luck. I've tried variations of openssl_pkcs7_sign and openssl_pkcs7_encrypt. I believe the issue is that there is no flag to indicate the DER format output.

Here is the openssl command I am trying to replicate:

openssl smime -sign -signer mycert.pem -certfile mybundle.crt -inkey mykey.pem -nodetach -outform der -in file_in -out file_out
like image 825
bobcat Avatar asked Oct 23 '25 17:10

bobcat


1 Answers

openssl_pkcs7_sign indeed signs the data in PEM format but you can just take the base64 chunk of the PEM data and convert it to DER by using base64_decode().

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!")
}
?>
like image 143
Viesturs Eihentals Avatar answered Oct 25 '25 08:10

Viesturs Eihentals



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!