Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.
According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.
When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.
$headers = array("To" => "email@example.com",
"From" => "firstname.lastname@example.org",
"Subject" => "A signed and encrypted message.");
$pubkey = file_get_contents("cert.pem");
$data = file_get_contents("enc.txt");
$parts = explode("\n\n", $data, 2);
mail($mail, $subject, $parts, $parts);
Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.
When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.
THIS IS WRONG!:
$signedOutputArray = signMessage($inputMessage,$headers);
$signedAndEncryptedArray = encryptMessage($signedOutputArray,
THIS IS CORRECT!
$signedOutputArray = signMessage($inputMessage,array());
encryptMessage($signedOutputArray . "\n\n" . $signedOutputArray,$headers);