SMimeSigner.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 SMimeSigner extends SMime
  17. {
  18. private $signCertificate;
  19. private $signPrivateKey;
  20. private $signOptions;
  21. private $extraCerts;
  22. /**
  23. * @param string $certificate The path of the file containing the signing certificate (in PEM format)
  24. * @param string $privateKey The path of the file containing the private key (in PEM format)
  25. * @param string|null $privateKeyPassphrase A passphrase of the private key (if any)
  26. * @param string|null $extraCerts The path of the file containing intermediate certificates (in PEM format) needed by the signing certificate
  27. * @param int|null $signOptions Bitwise operator options for openssl_pkcs7_sign() (@see https://secure.php.net/manual/en/openssl.pkcs7.flags.php)
  28. */
  29. public function __construct(string $certificate, string $privateKey, string $privateKeyPassphrase = null, string $extraCerts = null, int $signOptions = null)
  30. {
  31. if (!\extension_loaded('openssl')) {
  32. throw new \LogicException('PHP extension "openssl" is required to use SMime.');
  33. }
  34. $this->signCertificate = $this->normalizeFilePath($certificate);
  35. if (null !== $privateKeyPassphrase) {
  36. $this->signPrivateKey = [$this->normalizeFilePath($privateKey), $privateKeyPassphrase];
  37. } else {
  38. $this->signPrivateKey = $this->normalizeFilePath($privateKey);
  39. }
  40. $this->signOptions = $signOptions ?? \PKCS7_DETACHED;
  41. $this->extraCerts = $extraCerts ? realpath($extraCerts) : null;
  42. }
  43. public function sign(Message $message): Message
  44. {
  45. $bufferFile = tmpfile();
  46. $outputFile = tmpfile();
  47. $this->iteratorToFile($message->getBody()->toIterable(), $bufferFile);
  48. if (!@openssl_pkcs7_sign(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->signCertificate, $this->signPrivateKey, [], $this->signOptions, $this->extraCerts)) {
  49. throw new RuntimeException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
  50. }
  51. return new Message($message->getHeaders(), $this->convertMessageToSMimePart($outputFile, 'multipart', 'signed'));
  52. }
  53. }