phpcodeigniterdigital-signaturepfx

How to create a detached P7S file with PHP?


I have an specific need: in my software I generate a a TXT document and I need to sign this file using a CAdES method and generate a detached P7S file, but I didn't find nothing about how to do this.

So what is my step-by-step

I tried to use the function openssl_pkcs7_sign, but I have only an error HTTP 500 and didn't catch any Exception, so I really have no idea what happened.

This is an simple example about what I tried (I made a lot of different calls on this function, that is the last one):

// the message you want to sign so that recipient can be sure it was you that
    // sent it
    $data = 'Here is the content';

    // save message to file
    $fp = fopen("licence.txt", "w");
    fwrite($fp, $data);
    fclose($fp);

    // encrypt it
    if (openssl_pkcs7_sign("license.txt", "licence.txt.p7s", "my_pfx_file.pfx",
       array("file://some_folder/my_pfx_file.pfx"),
       null
       )) {
       // message signed - send it!
       exit('foi');
    } else {
        exit('falhou');
    }

I hope somebody can help me!


Solution

  • According to documentation, the key and cert should be either an entities, strings in 'file://...' format, or files' content.

    I wasn't able to use 'file://...' format for some reason, so I had to use openssl_x509_read for certificate and openssl_pkey_get_private for a key. Also, if you use an array in some argument, it expects key at 0 index and passphrase at 1.

    For any errors take a look at openssl_error_string, it would contain any error whenever you get false from those methods.

    Hope this helps!