SMimeEncrypter.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime\Crypto;
  11. use Symfony\Component\Mime\Exception\RuntimeException;
  12. use Symfony\Component\Mime\Message;
  13. /**
  14. * @author Sebastiaan Stok <s.stok@rollerscapes.net>
  15. */
  16. final class SMimeEncrypter extends SMime
  17. {
  18. private $certs;
  19. private $cipher;
  20. /**
  21. * @param string|string[] $certificate The path (or array of paths) of the file(s) containing the X.509 certificate(s)
  22. * @param int|null $cipher A set of algorithms used to encrypt the message. Must be one of these PHP constants: https://www.php.net/manual/en/openssl.ciphers.php
  23. */
  24. public function __construct($certificate, int $cipher = null)
  25. {
  26. if (!\extension_loaded('openssl')) {
  27. throw new \LogicException('PHP extension "openssl" is required to use SMime.');
  28. }
  29. if (\is_array($certificate)) {
  30. $this->certs = array_map([$this, 'normalizeFilePath'], $certificate);
  31. } else {
  32. $this->certs = $this->normalizeFilePath($certificate);
  33. }
  34. $this->cipher = $cipher ?? OPENSSL_CIPHER_AES_256_CBC;
  35. }
  36. public function encrypt(Message $message): Message
  37. {
  38. $bufferFile = tmpfile();
  39. $outputFile = tmpfile();
  40. $this->iteratorToFile($message->toIterable(), $bufferFile);
  41. if (!@openssl_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->certs, [], 0, $this->cipher)) {
  42. throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
  43. }
  44. $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime');
  45. $mimePart->getHeaders()
  46. ->addTextHeader('Content-Transfer-Encoding', 'base64')
  47. ->addParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'smime.p7m'])
  48. ;
  49. return new Message($message->getHeaders(), $mimePart);
  50. }
  51. }