3 * @file src/Util/Crypto.php
5 namespace Friendica\Util;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
20 // supported algorithms are 'sha256', 'sha1'
22 * @param string $data data
23 * @param string $key key
24 * @param string $alg algorithm
27 public static function rsaSign($data, $key, $alg = 'sha256')
30 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
32 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
37 * @param string $data data
38 * @param string $sig signature
39 * @param string $key key
40 * @param string $alg algorithm
43 public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
46 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
48 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
52 * @param string $Der der formatted string
53 * @param bool $Private key type optional, default false
56 private static function DerToPem($Der, $Private = false)
59 $Der = base64_encode($Der);
61 $lines = str_split($Der, 65);
62 $body = implode("\n", $lines);
64 $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
66 $result = "-----BEGIN {$title}-----\n";
67 $result .= $body . "\n";
68 $result .= "-----END {$title}-----\n";
74 * @param string $Der der formatted string
77 private static function DerToRsa($Der)
80 $Der = base64_encode($Der);
82 $lines = str_split($Der, 64);
83 $body = implode("\n", $lines);
85 $title = 'RSA PUBLIC KEY';
87 $result = "-----BEGIN {$title}-----\n";
88 $result .= $body . "\n";
89 $result .= "-----END {$title}-----\n";
95 * @param string $Modulus modulo
96 * @param string $PublicExponent exponent
99 private static function pkcs8Encode($Modulus, $PublicExponent)
101 //Encode key sequence
102 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
103 $modulus->SetIntBuffer($Modulus);
104 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
105 $publicExponent->SetIntBuffer($PublicExponent);
106 $keySequenceItems = [$modulus, $publicExponent];
107 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
108 $keySequence->SetSequence($keySequenceItems);
110 $bitStringValue = $keySequence->Encode();
111 $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
112 $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
113 $bitString->Value = $bitStringValue;
115 $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
116 $body = new ASNValue(ASNValue::TAG_SEQUENCE);
117 $body->Value = $bodyValue;
118 //Get DER encoded public key:
119 $PublicDER = $body->Encode();
124 * @param string $Modulus modulo
125 * @param string $PublicExponent exponent
128 private static function pkcs1Encode($Modulus, $PublicExponent)
130 //Encode key sequence
131 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
132 $modulus->SetIntBuffer($Modulus);
133 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
134 $publicExponent->SetIntBuffer($PublicExponent);
135 $keySequenceItems = [$modulus, $publicExponent];
136 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
137 $keySequence->SetSequence($keySequenceItems);
139 $bitStringValue = $keySequence->Encode();
140 return $bitStringValue;
144 * @param string $m modulo
145 * @param string $e exponent
148 public static function meToPem($m, $e)
150 $der = self::pkcs8Encode($m, $e);
151 $key = self::DerToPem($der, false);
156 * @param string $key key
157 * @param string $m modulo reference
158 * @param object $e exponent reference
162 private static function pubRsaToMe($key, &$m, &$e)
164 $lines = explode("\n", $key);
166 unset($lines[count($lines)]);
167 $x = base64_decode(implode('', $lines));
169 $r = ASN_BASE::parseASNString($x);
171 $m = Strings::base64UrlDecode($r[0]->asnData[0]->asnData);
172 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData);
176 * @param string $key key
180 public static function rsaToPem($key)
182 self::pubRsaToMe($key, $m, $e);
183 return self::meToPem($m, $e);
187 * @param string $key key
191 private static function pemToRsa($key)
193 self::pemToMe($key, $m, $e);
194 return self::meToRsa($m, $e);
198 * @param string $key key
199 * @param string $m modulo reference
200 * @param string $e exponent reference
204 public static function pemToMe($key, &$m, &$e)
206 $lines = explode("\n", $key);
208 unset($lines[count($lines)]);
209 $x = base64_decode(implode('', $lines));
211 $r = ASN_BASE::parseASNString($x);
214 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
215 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
220 * @param string $m modulo
221 * @param string $e exponent
224 private static function meToRsa($m, $e)
226 $der = self::pkcs1Encode($m, $e);
227 $key = self::DerToRsa($der);
232 * @param integer $bits number of bits
234 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
236 public static function newKeypair($bits)
239 'digest_alg' => 'sha1',
240 'private_key_bits' => $bits,
241 'encrypt_key' => false
244 $conf = DI::config()->get('system', 'openssl_conf_file');
246 $openssl_options['config'] = $conf;
248 $result = openssl_pkey_new($openssl_options);
250 if (empty($result)) {
251 Logger::log('new_keypair: failed');
256 $response = ['prvkey' => '', 'pubkey' => ''];
258 openssl_pkey_export($result, $response['prvkey']);
261 $pkey = openssl_pkey_get_details($result);
262 $response['pubkey'] = $pkey["key"];
268 * Encrypt a string with 'aes-256-cbc' cipher method.
270 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
272 * @param string $data
273 * @param string $key The key used for encryption.
274 * @param string $iv A non-NULL Initialization Vector.
276 * @return string|boolean Encrypted string or false on failure.
278 private static function encryptAES256CBC($data, $key, $iv)
280 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
284 * Decrypt a string with 'aes-256-cbc' cipher method.
286 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
288 * @param string $data
289 * @param string $key The key used for decryption.
290 * @param string $iv A non-NULL Initialization Vector.
292 * @return string|boolean Decrypted string or false on failure.
294 private static function decryptAES256CBC($data, $key, $iv)
296 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
300 * Encrypt a string with 'aes-256-ctr' cipher method.
302 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
304 * @param string $data
305 * @param string $key The key used for encryption.
306 * @param string $iv A non-NULL Initialization Vector.
308 * @return string|boolean Encrypted string or false on failure.
310 private static function encryptAES256CTR($data, $key, $iv)
312 $key = substr($key, 0, 32);
313 $iv = substr($iv, 0, 16);
314 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
318 * Decrypt a string with 'aes-256-ctr' cipher method.
320 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
322 * @param string $data
323 * @param string $key The key used for decryption.
324 * @param string $iv A non-NULL Initialization Vector.
326 * @return string|boolean Decrypted string or false on failure.
328 private static function decryptAES256CTR($data, $key, $iv)
330 $key = substr($key, 0, 32);
331 $iv = substr($iv, 0, 16);
332 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
337 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
339 * @param string $data
340 * @param string $pubkey The public key.
341 * @param string $alg The algorithm used for encryption.
346 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
348 if ($alg === 'aes256cbc') {
349 return self::encapsulateAes($data, $pubkey);
351 return self::encapsulateOther($data, $pubkey, $alg);
356 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
358 * @param string $data
359 * @param string $pubkey The public key.
360 * @param string $alg The algorithm used for encryption.
365 private static function encapsulateOther($data, $pubkey, $alg)
368 Logger::log('no key. data: '.$data);
370 $fn = 'encrypt' . strtoupper($alg);
371 if (method_exists(__CLASS__, $fn)) {
372 $result = ['encrypted' => true];
373 $key = random_bytes(256);
374 $iv = random_bytes(256);
375 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
377 // log the offending call so we can track it down
378 if (!openssl_public_encrypt($key, $k, $pubkey)) {
379 $x = debug_backtrace();
380 Logger::log('RSA failed. ' . print_r($x[0], true));
383 $result['alg'] = $alg;
384 $result['key'] = Strings::base64UrlEncode($k, true);
385 openssl_public_encrypt($iv, $i, $pubkey);
386 $result['iv'] = Strings::base64UrlEncode($i, true);
390 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
391 Hook::callAll('other_encapsulate', $x);
399 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
401 * @param string $data
402 * @param string $pubkey
407 private static function encapsulateAes($data, $pubkey)
410 Logger::log('aes_encapsulate: no key. data: ' . $data);
413 $key = random_bytes(32);
414 $iv = random_bytes(16);
415 $result = ['encrypted' => true];
416 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
418 // log the offending call so we can track it down
419 if (!openssl_public_encrypt($key, $k, $pubkey)) {
420 $x = debug_backtrace();
421 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
424 $result['alg'] = 'aes256cbc';
425 $result['key'] = Strings::base64UrlEncode($k, true);
426 openssl_public_encrypt($iv, $i, $pubkey);
427 $result['iv'] = Strings::base64UrlEncode($i, true);
434 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
436 * @param array $data ['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data]
437 * @param string $prvkey The private key used for decryption.
439 * @return string|boolean The decrypted string or false on failure.
442 public static function unencapsulate(array $data, $prvkey)
448 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
449 if ($alg === 'aes256cbc') {
450 return self::encapsulateAes($data['data'], $prvkey);
452 return self::encapsulateOther($data['data'], $prvkey, $alg);
457 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
460 * @param string $prvkey The private key used for decryption.
463 * @return string|boolean The decrypted string or false on failure.
464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
466 private static function unencapsulateOther(array $data, $prvkey, $alg)
468 $fn = 'decrypt' . strtoupper($alg);
470 if (method_exists(__CLASS__, $fn)) {
471 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
472 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
474 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
476 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
477 Hook::callAll('other_unencapsulate', $x);
485 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
488 * @param string $prvkey The private key used for decryption.
490 * @return string|boolean The decrypted string or false on failure.
493 private static function unencapsulateAes($data, $prvkey)
495 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
496 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
498 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
503 * Creates cryptographic secure random digits
505 * @param string $digits The count of digits
506 * @return int The random Digits
508 * @throws \Exception In case 'random_int' isn't usable
510 public static function randomDigits($digits)
514 // generating cryptographically secure pseudo-random integers
515 for ($i = 0; $i < $digits; $i++) {
516 $rn .= random_int(0, 9);