SMimeSigner.php 2.8 KB

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