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