Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Cryptographer.php
Go to the documentation of this file.
1 <?php
7 
9 
14 {
20  private $analyticsToken;
21 
27  private $cipherMethod = 'AES-256-CBC';
28 
32  private $encodedContextFactory;
33 
38  public function __construct(
39  AnalyticsToken $analyticsToken,
40  EncodedContextFactory $encodedContextFactory
41  ) {
42  $this->analyticsToken = $analyticsToken;
43  $this->encodedContextFactory = $encodedContextFactory;
44  }
45 
53  public function encode($source)
54  {
55  if (!is_string($source)) {
56  try {
57  $source = (string)$source;
58  } catch (\Exception $e) {
59  throw new LocalizedException(
60  __(
61  'The data is invalid. '
62  . 'Enter the data as a string or data that can be converted into a string and try again.'
63  )
64  );
65  }
66  } elseif (!$source) {
67  throw new LocalizedException(__('The data is invalid. Enter the data as a string and try again.'));
68  }
69  if (!$this->validateCipherMethod($this->cipherMethod)) {
70  throw new LocalizedException(__('The data is invalid. Use a valid cipher method and try again.'));
71  }
72  $initializationVector = $this->getInitializationVector();
73 
74  $encodedContext = $this->encodedContextFactory->create([
75  'content' => openssl_encrypt(
76  $source,
77  $this->cipherMethod,
78  $this->getKey(),
79  OPENSSL_RAW_DATA,
80  $initializationVector
81  ),
82  'initializationVector' => $initializationVector,
83  ]);
84 
85  return $encodedContext;
86  }
87 
94  private function getKey()
95  {
96  $token = $this->analyticsToken->getToken();
97  if (!$token) {
98  throw new LocalizedException(__('Enter the encryption key and try again.'));
99  }
100  return hash('sha256', $token);
101  }
102 
108  private function getCipherMethod()
109  {
110  return $this->cipherMethod;
111  }
112 
118  private function getInitializationVector()
119  {
120  $ivSize = openssl_cipher_iv_length($this->getCipherMethod());
121  return openssl_random_pseudo_bytes($ivSize);
122  }
123 
130  private function validateCipherMethod($cipherMethod)
131  {
132  $methods = openssl_get_cipher_methods();
133  return (false !== array_search($cipherMethod, $methods));
134  }
135 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$source
Definition: source.php:23
__()
Definition: __.php:13
$methods
Definition: billing.phtml:71
__construct(AnalyticsToken $analyticsToken, EncodedContextFactory $encodedContextFactory)