1

I am on Win 10/PHP 7.3/Laravel and I am trying to sign a PDF using certificate files generated by:

openssl genrsa -out my-private-key.pem 2048
openssl req -new -key my-private-key.pem -x509 -days 3650 -out my-public-key.pem

But when I open the bearing_signed.pdf, it doesn't contain a signature. Below is my code block I am currently using:

        openssl_pkcs7_sign(
          $app_path . 'bearing.pdf',
          $app_path . 'bearing_signed.pdf',
          "file://" . $app_path . "my-public-key.pem",
          array("file://" . $app_path . "my-private-key.pem", ""),
          array(
            "To" => $to_email,
            "From" => env('MAIL_FROM_NAME') . '<' . env('MAIL_FROM_ADDRESS') . '>',
            "Subject" => $data['subject']
          ),
          PKCS7_BINARY
        );

        // convert PEM to DER
        $pem_data = file_get_contents($app_path . 'bearing_signed.pdf');
        $begin = "Content-Transfer-Encoding: base64";
        $pem_data = trim(substr($pem_data, strpos($pem_data, $begin) + strlen($begin)));
        $der = base64_decode($pem_data);

        $fp = fopen($app_path . 'bearing_signed.pdf', "w");
        if ($fp) {
          fwrite($fp, $der);
          fclose($fp);
        }

what can be the problem with this code?

Lakmal Premaratne
  • 1,159
  • 7
  • 18
  • 34
  • 1
    Generally, one would require to sign PDF not using self signed certificate but using Certificates issued by Certifying Authorities... Please refer to [SO answer](https://stackoverflow.com/a/55696238/9659885) if it can be useful to you... – Bharat Vasant Jul 01 '20 at 06:09
  • Sorry but what do you mean when you say that "when I open the bearing_signed.pdf, it doesn't contain a signature"? Did you expect to have a PDF document that has been signed? Or did you expect to have the signature itself? – Carlos Sep 23 '22 at 07:44

1 Answers1

0

I found a better solution to sign, but not only with PHP. You'll need to used the exec() command to do this.

1 - Need to install java. Linux sudo apt install /select_folder/default-jre

2 - Need to instal Portable Signer. Download the ZIP file and run the file jar ( https://sourceforge.net/projects/portablesigner/files/portablesigner/2.0-Release/PortableSigner-Generic-2.0.38c0573.zip/download ). Linux sudo java -jar /select_folder/PortableSigner.jar

3 - After install Portable Signer and choose the installation folder execute the app using the manual ( http://portablesigner.sourceforge.net/ ) with command exec() in php.

Example: exec("java -jar PortableSigner.jar -n /Users/pfp/Desktop/unsigned.pdf -o /Users/pfp/Desktop/signed.pdf -s /Users/pfp/Desktop/certificate.pfx -p MySecretPassword");

In documentation you have many options to sign. I hope this ll help a lot the PHP comumunity here.