3 * @file src/Util/Crypto.php
5 namespace Friendica\Util;
7 use Friendica\Core\Config;
8 use Friendica\Core\Hook;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
19 // supported algorithms are 'sha256', 'sha1'
21 * @param string $data data
22 * @param string $key key
23 * @param string $alg algorithm
26 public static function rsaSign($data, $key, $alg = 'sha256')
29 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
31 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
36 * @param string $data data
37 * @param string $sig signature
38 * @param string $key key
39 * @param string $alg algorithm
42 public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
45 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
47 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
51 * @param string $Der der formatted string
52 * @param bool $Private key type optional, default false
55 private static function DerToPem($Der, $Private = false)
58 $Der = base64_encode($Der);
60 $lines = str_split($Der, 65);
61 $body = implode("\n", $lines);
63 $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
65 $result = "-----BEGIN {$title}-----\n";
66 $result .= $body . "\n";
67 $result .= "-----END {$title}-----\n";
73 * @param string $Der der formatted string
76 private static function DerToRsa($Der)
79 $Der = base64_encode($Der);
81 $lines = str_split($Der, 64);
82 $body = implode("\n", $lines);
84 $title = 'RSA PUBLIC KEY';
86 $result = "-----BEGIN {$title}-----\n";
87 $result .= $body . "\n";
88 $result .= "-----END {$title}-----\n";
94 * @param string $Modulus modulo
95 * @param string $PublicExponent exponent
98 private static function pkcs8Encode($Modulus, $PublicExponent)
100 //Encode key sequence
101 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
102 $modulus->SetIntBuffer($Modulus);
103 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
104 $publicExponent->SetIntBuffer($PublicExponent);
105 $keySequenceItems = [$modulus, $publicExponent];
106 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
107 $keySequence->SetSequence($keySequenceItems);
109 $bitStringValue = $keySequence->Encode();
110 $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
111 $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
112 $bitString->Value = $bitStringValue;
114 $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
115 $body = new ASNValue(ASNValue::TAG_SEQUENCE);
116 $body->Value = $bodyValue;
117 //Get DER encoded public key:
118 $PublicDER = $body->Encode();
123 * @param string $Modulus modulo
124 * @param string $PublicExponent exponent
127 private static function pkcs1Encode($Modulus, $PublicExponent)
129 //Encode key sequence
130 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
131 $modulus->SetIntBuffer($Modulus);
132 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
133 $publicExponent->SetIntBuffer($PublicExponent);
134 $keySequenceItems = [$modulus, $publicExponent];
135 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
136 $keySequence->SetSequence($keySequenceItems);
138 $bitStringValue = $keySequence->Encode();
139 return $bitStringValue;
143 * @param string $m modulo
144 * @param string $e exponent
147 public static function meToPem($m, $e)
149 $der = self::pkcs8Encode($m, $e);
150 $key = self::DerToPem($der, false);
155 * @param string $key key
156 * @param string $m modulo reference
157 * @param object $e exponent reference
161 private static function pubRsaToMe($key, &$m, &$e)
163 $lines = explode("\n", $key);
165 unset($lines[count($lines)]);
166 $x = base64_decode(implode('', $lines));
168 $r = ASN_BASE::parseASNString($x);
170 $m = Strings::base64UrlDecode($r[0]->asnData[0]->asnData);
171 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData);
175 * @param string $key key
179 public static function rsaToPem($key)
181 self::pubRsaToMe($key, $m, $e);
182 return self::meToPem($m, $e);
186 * @param string $key key
190 private static function pemToRsa($key)
192 self::pemToMe($key, $m, $e);
193 return self::meToRsa($m, $e);
197 * @param string $key key
198 * @param string $m modulo reference
199 * @param string $e exponent reference
203 public static function pemToMe($key, &$m, &$e)
205 $lines = explode("\n", $key);
207 unset($lines[count($lines)]);
208 $x = base64_decode(implode('', $lines));
210 $r = ASN_BASE::parseASNString($x);
212 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
213 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
217 * @param string $m modulo
218 * @param string $e exponent
221 private static function meToRsa($m, $e)
223 $der = self::pkcs1Encode($m, $e);
224 $key = self::DerToRsa($der);
229 * @param integer $bits number of bits
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 public static function newKeypair($bits)
236 'digest_alg' => 'sha1',
237 'private_key_bits' => $bits,
238 'encrypt_key' => false
241 $conf = Config::get('system', 'openssl_conf_file');
243 $openssl_options['config'] = $conf;
245 $result = openssl_pkey_new($openssl_options);
247 if (empty($result)) {
248 Logger::log('new_keypair: failed');
253 $response = ['prvkey' => '', 'pubkey' => ''];
255 openssl_pkey_export($result, $response['prvkey']);
258 $pkey = openssl_pkey_get_details($result);
259 $response['pubkey'] = $pkey["key"];
265 * Encrypt a string with 'aes-256-cbc' cipher method.
267 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
269 * @param string $data
270 * @param string $key The key used for encryption.
271 * @param string $iv A non-NULL Initialization Vector.
273 * @return string|boolean Encrypted string or false on failure.
275 private static function encryptAES256CBC($data, $key, $iv)
277 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
281 * Decrypt a string with 'aes-256-cbc' cipher method.
283 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
285 * @param string $data
286 * @param string $key The key used for decryption.
287 * @param string $iv A non-NULL Initialization Vector.
289 * @return string|boolean Decrypted string or false on failure.
291 private static function decryptAES256CBC($data, $key, $iv)
293 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
297 * Encrypt a string with 'aes-256-ctr' cipher method.
299 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
301 * @param string $data
302 * @param string $key The key used for encryption.
303 * @param string $iv A non-NULL Initialization Vector.
305 * @return string|boolean Encrypted string or false on failure.
307 private static function encryptAES256CTR($data, $key, $iv)
309 $key = substr($key, 0, 32);
310 $iv = substr($iv, 0, 16);
311 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
315 * Decrypt a string with 'aes-256-ctr' cipher method.
317 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
319 * @param string $data
320 * @param string $key The key used for decryption.
321 * @param string $iv A non-NULL Initialization Vector.
323 * @return string|boolean Decrypted string or false on failure.
325 private static function decryptAES256CTR($data, $key, $iv)
327 $key = substr($key, 0, 32);
328 $iv = substr($iv, 0, 16);
329 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
334 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
336 * @param string $data
337 * @param string $pubkey The public key.
338 * @param string $alg The algorithm used for encryption.
343 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
345 if ($alg === 'aes256cbc') {
346 return self::encapsulateAes($data, $pubkey);
348 return self::encapsulateOther($data, $pubkey, $alg);
353 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
355 * @param string $data
356 * @param string $pubkey The public key.
357 * @param string $alg The algorithm used for encryption.
362 private static function encapsulateOther($data, $pubkey, $alg)
365 Logger::log('no key. data: '.$data);
367 $fn = 'encrypt' . strtoupper($alg);
368 if (method_exists(__CLASS__, $fn)) {
369 $result = ['encrypted' => true];
370 $key = random_bytes(256);
371 $iv = random_bytes(256);
372 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
374 // log the offending call so we can track it down
375 if (!openssl_public_encrypt($key, $k, $pubkey)) {
376 $x = debug_backtrace();
377 Logger::log('RSA failed. ' . print_r($x[0], true));
380 $result['alg'] = $alg;
381 $result['key'] = Strings::base64UrlEncode($k, true);
382 openssl_public_encrypt($iv, $i, $pubkey);
383 $result['iv'] = Strings::base64UrlEncode($i, true);
387 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
388 Hook::callAll('other_encapsulate', $x);
396 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
398 * @param string $data
399 * @param string $pubkey
404 private static function encapsulateAes($data, $pubkey)
407 Logger::log('aes_encapsulate: no key. data: ' . $data);
410 $key = random_bytes(32);
411 $iv = random_bytes(16);
412 $result = ['encrypted' => true];
413 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
415 // log the offending call so we can track it down
416 if (!openssl_public_encrypt($key, $k, $pubkey)) {
417 $x = debug_backtrace();
418 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
421 $result['alg'] = 'aes256cbc';
422 $result['key'] = Strings::base64UrlEncode($k, true);
423 openssl_public_encrypt($iv, $i, $pubkey);
424 $result['iv'] = Strings::base64UrlEncode($i, true);
431 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
433 * @param array $data ['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data]
434 * @param string $prvkey The private key used for decryption.
436 * @return string|boolean The decrypted string or false on failure.
439 public static function unencapsulate(array $data, $prvkey)
445 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
446 if ($alg === 'aes256cbc') {
447 return self::encapsulateAes($data['data'], $prvkey);
449 return self::encapsulateOther($data['data'], $prvkey, $alg);
454 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
457 * @param string $prvkey The private key used for decryption.
460 * @return string|boolean The decrypted string or false on failure.
461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
463 private static function unencapsulateOther(array $data, $prvkey, $alg)
465 $fn = 'decrypt' . strtoupper($alg);
467 if (method_exists(__CLASS__, $fn)) {
468 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
469 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
471 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
473 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
474 Hook::callAll('other_unencapsulate', $x);
482 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
485 * @param string $prvkey The private key used for decryption.
487 * @return string|boolean The decrypted string or false on failure.
490 private static function unencapsulateAes($data, $prvkey)
492 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
493 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
495 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
500 * Creates cryptographic secure random digits
502 * @param string $digits The count of digits
503 * @return int The random Digits
505 * @throws \Exception In case 'random_int' isn't usable
507 public static function randomDigits($digits)
511 // generating cryptographically secure pseudo-random integers
512 for ($i = 0; $i < $digits; $i++) {
513 $rn .= random_int(0, 9);