From ce0eeb7c4527d5dc6af7d7ac7a967a4c7b4f63c7 Mon Sep 17 00:00:00 2001 From: ratatine Date: Fri, 30 Nov 2018 12:30:34 -0600 Subject: [PATCH] Support for SMIME for digital signing and encryption of message --- src/PHPMailer.php | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/PHPMailer.php b/src/PHPMailer.php index a3be338b..1dfe600e 100644 --- a/src/PHPMailer.php +++ b/src/PHPMailer.php @@ -682,6 +682,20 @@ class PHPMailer */ protected $sign_key_pass = ''; + /** + * An array of public PEM encoded certificates for each recipient + * @var array + * @access protected + */ + protected $encrypt_recipcerts = array(); + + /** + * Used if body should be S/MIME encrypted + * @var bool + * @access protected + */ + protected $encrypt_body = false; + /** * Whether to throw exceptions for errors. * @@ -2684,6 +2698,33 @@ class PHPMailer @unlink($signed); throw new Exception($this->lang('signing') . openssl_error_string()); } + + if($this->encrypt_body) { + + // Write out the encrypted message + $file = tempnam(sys_get_temp_dir(), "mail"); + if (false === file_put_contents($file, $this->MIMEHeader . static::$LE . static::$LE . $body)) { + throw new phpmailerException($this->lang('encrypting') . ' Could not write temp file'); + } + $encrypted = tempnam(sys_get_temp_dir(), 'encrypted'); + + $encrypt = openssl_pkcs7_encrypt($file, $encrypted, $this->encrypt_recipcerts, array()); + if ($encrypt) { + @unlink($file); + $body = file_get_contents($encrypted); + // As with signing, the headers get rewriting after encrypting + $parts = explode("\n\n", $body, 2); + $this->MIMEHeader = $parts[0] . static::$LE . static::$LE; + $body = $parts[1]; + @unlink($encrypted); + } else { + @unlink($file); + @unlink($encrypted); + throw new phpmailerException($this->lang('encrypting') . openssl_error_string()); + } + + } + } catch (Exception $exc) { $body = ''; if ($this->exceptions) { @@ -4157,6 +4198,17 @@ class PHPMailer $this->sign_extracerts_file = $extracerts_filename; } + /** + * Set the certificates, keys and passwords to encrypt via S/MIME + * @param array $recipcerts Array of certificates used for recipients in PEM format + */ + public function add_encryption($recipcert_file) + { + $this->encrypt_body = true; + $cert = file_get_contents($recipcert_file); + array_push($this->encrypt_recipcerts, $cert); + } + /** * Quoted-Printable-encode a DKIM header. *