Open Journal Systems  3.3.0
SMimeEncrypter.php
1 <?php
2 
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11 
13 
16 
20 final class SMimeEncrypter extends SMime
21 {
22  private $certs;
23  private $cipher;
24 
29  public function __construct($certificate, int $cipher = null)
30  {
31  if (!\extension_loaded('openssl')) {
32  throw new \LogicException('PHP extension "openssl" is required to use SMime.');
33  }
34 
35  if (\is_array($certificate)) {
36  $this->certs = array_map([$this, 'normalizeFilePath'], $certificate);
37  } else {
38  $this->certs = $this->normalizeFilePath($certificate);
39  }
40 
41  $this->cipher = $cipher ?? OPENSSL_CIPHER_AES_256_CBC;
42  }
43 
44  public function encrypt(Message $message): Message
45  {
46  $bufferFile = tmpfile();
47  $outputFile = tmpfile();
48 
49  $this->iteratorToFile($message->toIterable(), $bufferFile);
50 
51  if (!@openssl_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri'], stream_get_meta_data($outputFile)['uri'], $this->certs, [], 0, $this->cipher)) {
52  throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
53  }
54 
55  $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime');
56  $mimePart->getHeaders()
57  ->addTextHeader('Content-Transfer-Encoding', 'base64')
58  ->addParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'smime.p7m'])
59  ;
60 
61  return new Message($message->getHeaders(), $mimePart);
62  }
63 }
Symfony\Component\Mime\Exception\RuntimeException
Definition: vendor/symfony/mime/Exception/RuntimeException.php:17
Symfony\Component\Mime\Crypto\SMime\iteratorToFile
iteratorToFile(iterable $iterator, $stream)
Definition: SMime.php:33
Symfony\Component\Mime\Crypto\SMime\convertMessageToSMimePart
convertMessageToSMimePart($stream, string $type, string $subtype)
Definition: SMime.php:40
Symfony\Component\Mime\Message
Definition: Message.php:22
Symfony\Component\Mime\Crypto\SMimeEncrypter\__construct
__construct($certificate, int $cipher=null)
Definition: SMimeEncrypter.php:29
Symfony\Component\Mime\Message\toIterable
toIterable()
Definition: Message.php:113
Symfony\Component\Mime\Crypto
Definition: SMime.php:12
Symfony\Component\Mime\Crypto\SMime
Definition: SMime.php:22
Symfony\Component\Mime\Crypto\SMime\normalizeFilePath
normalizeFilePath(string $path)
Definition: SMime.php:24
Symfony\Component\Mime\Crypto\SMimeEncrypter\encrypt
encrypt(Message $message)
Definition: SMimeEncrypter.php:44
Symfony\Component\Mime\Crypto\SMimeEncrypter
Definition: SMimeEncrypter.php:20
Symfony\Component\Mime\Message\getHeaders
getHeaders()
Definition: Message.php:67