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