TYPO3 CMS  TYPO3_7-6
PhpBackend.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
23 {
32  public function createNewKeyPair()
33  {
35  $keyPair = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Rsaauth\Keypair::class);
36  if ($keyPair->isReady()) {
37  return $keyPair;
38  }
39 
40  $privateKey = @openssl_pkey_new();
41  if ($privateKey !== false) {
42  // Create private key as string
43  $privateKeyStr = '';
44  openssl_pkey_export($privateKey, $privateKeyStr);
45  // Prepare public key information
46  $exportedData = '';
47  $csr = openssl_csr_new([
48  'localityName' => 'foo',
49  'organizationName' => 'bar',
50  ], $privateKey);
51  openssl_csr_export($csr, $exportedData, false);
52  // Get public key (in fact modulus) and exponent
53  $publicKey = $this->extractPublicKeyModulus($exportedData);
54  $exponent = $this->extractExponent($exportedData);
55 
56  $keyPair->setExponent($exponent);
57  $keyPair->setPrivateKey($privateKeyStr);
58  $keyPair->setPublicKey($publicKey);
59  // Clean up all resources
60  openssl_free_key($privateKey);
61  } else {
62  $keyPair = null;
63  }
64 
65  return $keyPair;
66  }
67 
77  public function decrypt($privateKey, $data)
78  {
79  $result = '';
80  if (!@openssl_private_decrypt(base64_decode($data), $result, $privateKey)) {
81  $result = null;
82  }
83  return $result;
84  }
85 
93  public function isAvailable()
94  {
95  $result = false;
96  if (is_callable('openssl_pkey_new')) {
97  // PHP extension has to be configured properly. It
98  // can be installed and available but will not work unless
99  // properly configured. So we check if it works.
100  $testKey = @openssl_pkey_new();
101  if (is_resource($testKey)) {
102  openssl_free_key($testKey);
103  $result = true;
104  }
105  }
106  return $result;
107  }
108 
115  protected function extractExponent($data)
116  {
117  $index = strpos($data, 'Exponent: ');
118  // We do not check for '$index === FALSE' because the exponent is
119  // always there!
120  return (int)substr($data, $index + 10);
121  }
122 
129  protected function extractPublicKeyModulus($data)
130  {
131  $fragment = preg_replace('/.*Modulus.*?\\n(.*)Exponent:.*/ms', '\\1', $data);
132  $fragment = preg_replace('/[\\s\\n\\r:]/', '', $fragment);
133  return trim(strtoupper(substr($fragment, 2)));
134  }
135 }