]> git.mxchange.org Git - friendica.git/blob - src/Util/Crypto.php
Merge pull request #6439 from annando/issue-6438
[friendica.git] / src / Util / Crypto.php
1 <?php
2 /**
3  * @file src/Util/Crypto.php
4  */
5 namespace Friendica\Util;
6
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\Logger;
10 use Friendica\Util\Strings;
11 use ASN_BASE;
12 use ASNValue;
13
14 /**
15  * @brief Crypto class
16  */
17 class Crypto
18 {
19         // supported algorithms are 'sha256', 'sha1'
20         /**
21          * @param string $data data
22          * @param string $key  key
23          * @param string $alg  algorithm
24          * @return string
25          */
26         public static function rsaSign($data, $key, $alg = 'sha256')
27         {
28                 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
29                 return $sig;
30         }
31
32         /**
33          * @param string $data data
34          * @param string $sig  signature
35          * @param string $key  key
36          * @param string $alg  algorithm
37          * @return boolean
38          */
39         public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
40         {
41                 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
42         }
43
44         /**
45          * @param string $Der     der formatted string
46          * @param string $Private key type optional, default false
47          * @return string
48          */
49         private static function DerToPem($Der, $Private = false)
50         {
51                 //Encode:
52                 $Der = base64_encode($Der);
53                 //Split lines:
54                 $lines = str_split($Der, 65);
55                 $body = implode("\n", $lines);
56                 //Get title:
57                 $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
58                 //Add wrapping:
59                 $result = "-----BEGIN {$title}-----\n";
60                 $result .= $body . "\n";
61                 $result .= "-----END {$title}-----\n";
62
63                 return $result;
64         }
65
66         /**
67          * @param string $Der der formatted string
68          * @return string
69          */
70         private static function DerToRsa($Der)
71         {
72                 //Encode:
73                 $Der = base64_encode($Der);
74                 //Split lines:
75                 $lines = str_split($Der, 64);
76                 $body = implode("\n", $lines);
77                 //Get title:
78                 $title = 'RSA PUBLIC KEY';
79                 //Add wrapping:
80                 $result = "-----BEGIN {$title}-----\n";
81                 $result .= $body . "\n";
82                 $result .= "-----END {$title}-----\n";
83
84                 return $result;
85         }
86
87         /**
88          * @param string $Modulus        modulo
89          * @param string $PublicExponent exponent
90          * @return string
91          */
92         private static function pkcs8Encode($Modulus, $PublicExponent)
93         {
94                 //Encode key sequence
95                 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
96                 $modulus->SetIntBuffer($Modulus);
97                 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
98                 $publicExponent->SetIntBuffer($PublicExponent);
99                 $keySequenceItems = [$modulus, $publicExponent];
100                 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
101                 $keySequence->SetSequence($keySequenceItems);
102                 //Encode bit string
103                 $bitStringValue = $keySequence->Encode();
104                 $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
105                 $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
106                 $bitString->Value = $bitStringValue;
107                 //Encode body
108                 $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
109                 $body = new ASNValue(ASNValue::TAG_SEQUENCE);
110                 $body->Value = $bodyValue;
111                 //Get DER encoded public key:
112                 $PublicDER = $body->Encode();
113                 return $PublicDER;
114         }
115
116         /**
117          * @param string $Modulus        modulo
118          * @param string $PublicExponent exponent
119          * @return string
120          */
121         private static function pkcs1Encode($Modulus, $PublicExponent)
122         {
123                 //Encode key sequence
124                 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
125                 $modulus->SetIntBuffer($Modulus);
126                 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
127                 $publicExponent->SetIntBuffer($PublicExponent);
128                 $keySequenceItems = [$modulus, $publicExponent];
129                 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
130                 $keySequence->SetSequence($keySequenceItems);
131                 //Encode bit string
132                 $bitStringValue = $keySequence->Encode();
133                 return $bitStringValue;
134         }
135
136         /**
137          * @param string $m modulo
138          * @param string $e exponent
139          * @return string
140          */
141         public static function meToPem($m, $e)
142         {
143                 $der = self::pkcs8Encode($m, $e);
144                 $key = self::DerToPem($der, false);
145                 return $key;
146         }
147
148         /**
149          * @param string $key key
150          * @param string $m   modulo reference
151          * @param object $e   exponent reference
152          * @return void
153          */
154         private static function pubRsaToMe($key, &$m, &$e)
155         {
156                 $lines = explode("\n", $key);
157                 unset($lines[0]);
158                 unset($lines[count($lines)]);
159                 $x = base64_decode(implode('', $lines));
160
161                 $r = ASN_BASE::parseASNString($x);
162
163                 $m = Strings::base64UrlDecode($r[0]->asnData[0]->asnData);
164                 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData);
165         }
166
167         /**
168          * @param string $key key
169          * @return string
170          */
171         public static function rsaToPem($key)
172         {
173                 self::pubRsaToMe($key, $m, $e);
174                 return self::meToPem($m, $e);
175         }
176
177         /**
178          * @param string $key key
179          * @return string
180          */
181         private static function pemToRsa($key)
182         {
183                 self::pemToMe($key, $m, $e);
184                 return self::meToRsa($m, $e);
185         }
186
187         /**
188          * @param string $key key
189          * @param string $m   modulo reference
190          * @param string $e   exponent reference
191          * @return void
192          */
193         public static function pemToMe($key, &$m, &$e)
194         {
195                 $lines = explode("\n", $key);
196                 unset($lines[0]);
197                 unset($lines[count($lines)]);
198                 $x = base64_decode(implode('', $lines));
199
200                 $r = ASN_BASE::parseASNString($x);
201
202                 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
203                 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
204         }
205
206         /**
207          * @param string $m modulo
208          * @param string $e exponent
209          * @return string
210          */
211         private static function meToRsa($m, $e)
212         {
213                 $der = self::pkcs1Encode($m, $e);
214                 $key = self::DerToRsa($der);
215                 return $key;
216         }
217
218         /**
219          * @param integer $bits number of bits
220          * @return mixed
221          */
222         public static function newKeypair($bits)
223         {
224                 $openssl_options = [
225                         'digest_alg'       => 'sha1',
226                         'private_key_bits' => $bits,
227                         'encrypt_key'      => false
228                 ];
229
230                 $conf = Config::get('system', 'openssl_conf_file');
231                 if ($conf) {
232                         $openssl_options['config'] = $conf;
233                 }
234                 $result = openssl_pkey_new($openssl_options);
235
236                 if (empty($result)) {
237                         Logger::log('new_keypair: failed');
238                         return false;
239                 }
240
241                 // Get private key
242                 $response = ['prvkey' => '', 'pubkey' => ''];
243
244                 openssl_pkey_export($result, $response['prvkey']);
245
246                 // Get public key
247                 $pkey = openssl_pkey_get_details($result);
248                 $response['pubkey'] = $pkey["key"];
249
250                 return $response;
251         }
252
253         /**
254          * Encrypt a string with 'aes-256-cbc' cipher method.
255          * 
256          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
257          * 
258          * @param string $data
259          * @param string $key   The key used for encryption.
260          * @param string $iv    A non-NULL Initialization Vector.
261          * 
262          * @return string|boolean Encrypted string or false on failure.
263          */
264         private static function encryptAES256CBC($data, $key, $iv)
265         {
266                 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
267         }
268
269         /**
270          * Decrypt a string with 'aes-256-cbc' cipher method.
271          * 
272          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
273          * 
274          * @param string $data
275          * @param string $key   The key used for decryption.
276          * @param string $iv    A non-NULL Initialization Vector.
277          * 
278          * @return string|boolean Decrypted string or false on failure.
279          */
280         private static function decryptAES256CBC($data, $key, $iv)
281         {
282                 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
283         }
284
285         /**
286          * Encrypt a string with 'aes-256-ctr' cipher method.
287          * 
288          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
289          * 
290          * @param string $data
291          * @param string $key   The key used for encryption.
292          * @param string $iv    A non-NULL Initialization Vector.
293          * 
294          * @return string|boolean Encrypted string or false on failure.
295          */
296         private static function encryptAES256CTR($data, $key, $iv)
297         {
298                 $key = substr($key, 0, 32);
299                 $iv = substr($iv, 0, 16);
300                 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
301         }
302
303         /**
304          * Decrypt a string with 'aes-256-ctr' cipher method.
305          * 
306          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
307          * 
308          * @param string $data
309          * @param string $key   The key used for decryption.
310          * @param string $iv    A non-NULL Initialization Vector.
311          * 
312          * @return string|boolean Decrypted string or false on failure.
313          */
314         private static function decryptAES256CTR($data, $key, $iv)
315         {
316                 $key = substr($key, 0, 32);
317                 $iv = substr($iv, 0, 16);
318                 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
319         }
320
321         /**
322          * 
323          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
324          * 
325          * @param string $data
326          * @param string $pubkey The public key.
327          * @param string $alg    The algorithm used for encryption.
328          * 
329          * @return array
330          */
331         public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
332         {
333                 if ($alg === 'aes256cbc') {
334                         return self::encapsulateAes($data, $pubkey);
335                 }
336                 return self::encapsulateOther($data, $pubkey, $alg);
337         }
338
339         /**
340          * 
341          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
342          * 
343          * @param type $data
344          * @param type $pubkey The public key.
345          * @param type $alg    The algorithm used for encryption.
346          * 
347          * @return array
348          */
349         private static function encapsulateOther($data, $pubkey, $alg)
350         {
351                 if (!$pubkey) {
352                         Logger::log('no key. data: '.$data);
353                 }
354                 $fn = 'encrypt' . strtoupper($alg);
355                 if (method_exists(__CLASS__, $fn)) {
356                         $result = ['encrypted' => true];
357                         $key = random_bytes(256);
358                         $iv  = random_bytes(256);
359                         $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
360
361                         // log the offending call so we can track it down
362                         if (!openssl_public_encrypt($key, $k, $pubkey)) {
363                                 $x = debug_backtrace();
364                                 Logger::log('RSA failed. ' . print_r($x[0], true));
365                         }
366
367                         $result['alg'] = $alg;
368                         $result['key'] = Strings::base64UrlEncode($k, true);
369                         openssl_public_encrypt($iv, $i, $pubkey);
370                         $result['iv'] = Strings::base64UrlEncode($i, true);
371
372                         return $result;
373                 } else {
374                         $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
375                         Addon::callHooks('other_encapsulate', $x);
376
377                         return $x['result'];
378                 }
379         }
380
381         /**
382          * 
383          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
384          * 
385          * @param string $data
386          * @param string $pubkey
387          * 
388          * @return array
389          */
390         private static function encapsulateAes($data, $pubkey)
391         {
392                 if (!$pubkey) {
393                         Logger::log('aes_encapsulate: no key. data: ' . $data);
394                 }
395
396                 $key = random_bytes(32);
397                 $iv  = random_bytes(16);
398                 $result = ['encrypted' => true];
399                 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
400
401                 // log the offending call so we can track it down
402                 if (!openssl_public_encrypt($key, $k, $pubkey)) {
403                         $x = debug_backtrace();
404                         Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
405                 }
406
407                 $result['alg'] = 'aes256cbc';
408                 $result['key'] = Strings::base64UrlEncode($k, true);
409                 openssl_public_encrypt($iv, $i, $pubkey);
410                 $result['iv'] = Strings::base64UrlEncode($i, true);
411
412                 return $result;
413         }
414
415         /**
416          * 
417          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
418          * 
419          * @param string $data
420          * @param string $prvkey  The private key used for decryption.
421          * 
422          * @return string|boolean The decrypted string or false on failure.
423          */
424         public static function unencapsulate($data, $prvkey)
425         {
426                 if (!$data) {
427                         return;
428                 }
429
430                 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
431                 if ($alg === 'aes256cbc') {
432                         return self::encapsulateAes($data, $prvkey);
433                 }
434                 return self::encapsulateOther($data, $prvkey, $alg);
435         }
436
437         /**
438          * 
439          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
440          * 
441          * @param string $data
442          * @param string $prvkey  The private key used for decryption.
443          * @param string $alg
444          * 
445          * @return string|boolean The decrypted string or false on failure.
446          */
447         private static function unencapsulateOther($data, $prvkey, $alg)
448         {
449                 $fn = 'decrypt' . strtoupper($alg);
450
451                 if (method_exists(__CLASS__, $fn)) {
452                         openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
453                         openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
454
455                         return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
456                 } else {
457                         $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
458                         Addon::callHooks('other_unencapsulate', $x);
459
460                         return $x['result'];
461                 }
462         }
463
464         /**
465          * 
466          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
467          * 
468          * @param array  $data
469          * @param string $prvkey  The private key used for decryption.
470          * 
471          * @return string|boolean The decrypted string or false on failure.
472          */
473         private static function unencapsulateAes($data, $prvkey)
474         {
475                 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
476                 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
477
478                 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
479         }
480
481
482         /**
483          * Creates cryptographic secure random digits
484          *
485          * @param string $digits The count of digits
486          * @return int The random Digits
487          *
488          * @throws \Exception In case 'random_int' isn't usable
489          */
490         public static function randomDigits($digits)
491         {
492                 $rn = '';
493
494                 // generating cryptographically secure pseudo-random integers
495                 for ($i = 0; $i < $digits; $i++) {
496                         $rn .= random_int(0, 9);
497                 }
498
499                 return $rn;
500         }
501 }