Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CredentialStore.php
Go to the documentation of this file.
1 <?php
8 
13 
15 {
16  const ENCRYPTION_ALGO = "AES-256-CBC";
17 
23  private static $INSTANCE = null;
24 
30  private $iv = null;
31 
37  private $encodedKey = null;
38 
44  private $credentials = [];
45 
51  public static function getInstance()
52  {
53  if (self::$INSTANCE == null) {
54  self::$INSTANCE = new CredentialStore();
55  }
56 
57  return self::$INSTANCE;
58  }
59 
63  private function __construct()
64  {
65  $this->encodedKey = base64_encode(openssl_random_pseudo_bytes(16));
66  $this->iv = substr(hash('sha256', $this->encodedKey), 0, 16);
67  $creds = $this->readInCredentialsFile();
68  $this->credentials = $this->encryptCredFileContents($creds);
69  }
70 
78  public function getSecret($key)
79  {
80  if (!array_key_exists($key, $this->credentials)) {
81  throw new TestFrameworkException(
82  "{$key} not defined in .credentials, please provide a value in order to use this secret in a test."
83  );
84  }
85 
86  // log here for verbose config
87  if (MftfApplicationConfig::getConfig()->verboseEnabled()) {
88  LoggingUtil::getInstance()->getLogger(CredentialStore::class)->debug(
89  "retrieving secret for key name {$key}"
90  );
91  }
92 
93  return $this->credentials[$key] ?? null;
94  }
95 
102  private function readInCredentialsFile()
103  {
104  $credsFilePath = str_replace(
105  '.credentials.example',
106  '.credentials',
108  );
109 
110  if (!file_exists($credsFilePath)) {
111  throw new TestFrameworkException(
112  "Cannot find .credentials file, please create in "
113  . TESTS_BP . " in order to reference sensitive information"
114  );
115  }
116 
117  return file($credsFilePath, FILE_IGNORE_NEW_LINES);
118  }
119 
126  private function encryptCredFileContents($credContents)
127  {
128  $encryptedCreds = [];
129  foreach ($credContents as $credValue) {
130  if (substr($credValue, 0, 1) === '#' || empty($credValue)) {
131  continue;
132  }
133 
134  list($key, $value) = explode("=", $credValue);
135  if (!empty($value)) {
136  $encryptedCreds[$key] = openssl_encrypt(
137  $value,
138  self::ENCRYPTION_ALGO,
139  $this->encodedKey,
140  0,
141  $this->iv
142  );
143  }
144  }
145 
146  return $encryptedCreds;
147  }
148 
155  public function decryptSecretValue($value)
156  {
157  return openssl_decrypt($value, self::ENCRYPTION_ALGO, $this->encodedKey, 0, $this->iv);
158  }
159 }
$value
Definition: gender.phtml:16