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;
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);
213 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
214 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
219 * @param string $m modulo
220 * @param string $e exponent
223 private static function meToRsa($m, $e)
225 $der = self::pkcs1Encode($m, $e);
226 $key = self::DerToRsa($der);
231 * @param integer $bits number of bits
233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
235 public static function newKeypair($bits)
238 'digest_alg' => 'sha1',
239 'private_key_bits' => $bits,
240 'encrypt_key' => false
243 $conf = Config::get('system', 'openssl_conf_file');
245 $openssl_options['config'] = $conf;
247 $result = openssl_pkey_new($openssl_options);
249 if (empty($result)) {
250 Logger::log('new_keypair: failed');
255 $response = ['prvkey' => '', 'pubkey' => ''];
257 openssl_pkey_export($result, $response['prvkey']);
260 $pkey = openssl_pkey_get_details($result);
261 $response['pubkey'] = $pkey["key"];
267 * Encrypt a string with 'aes-256-cbc' cipher method.
269 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
271 * @param string $data
272 * @param string $key The key used for encryption.
273 * @param string $iv A non-NULL Initialization Vector.
275 * @return string|boolean Encrypted string or false on failure.
277 private static function encryptAES256CBC($data, $key, $iv)
279 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
283 * Decrypt a string with 'aes-256-cbc' cipher method.
285 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
287 * @param string $data
288 * @param string $key The key used for decryption.
289 * @param string $iv A non-NULL Initialization Vector.
291 * @return string|boolean Decrypted string or false on failure.
293 private static function decryptAES256CBC($data, $key, $iv)
295 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
299 * Encrypt a string with 'aes-256-ctr' cipher method.
301 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
303 * @param string $data
304 * @param string $key The key used for encryption.
305 * @param string $iv A non-NULL Initialization Vector.
307 * @return string|boolean Encrypted string or false on failure.
309 private static function encryptAES256CTR($data, $key, $iv)
311 $key = substr($key, 0, 32);
312 $iv = substr($iv, 0, 16);
313 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
317 * Decrypt a string with 'aes-256-ctr' cipher method.
319 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
321 * @param string $data
322 * @param string $key The key used for decryption.
323 * @param string $iv A non-NULL Initialization Vector.
325 * @return string|boolean Decrypted string or false on failure.
327 private static function decryptAES256CTR($data, $key, $iv)
329 $key = substr($key, 0, 32);
330 $iv = substr($iv, 0, 16);
331 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
336 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
338 * @param string $data
339 * @param string $pubkey The public key.
340 * @param string $alg The algorithm used for encryption.
345 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
347 if ($alg === 'aes256cbc') {
348 return self::encapsulateAes($data, $pubkey);
350 return self::encapsulateOther($data, $pubkey, $alg);
355 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
357 * @param string $data
358 * @param string $pubkey The public key.
359 * @param string $alg The algorithm used for encryption.
364 private static function encapsulateOther($data, $pubkey, $alg)
367 Logger::log('no key. data: '.$data);
369 $fn = 'encrypt' . strtoupper($alg);
370 if (method_exists(__CLASS__, $fn)) {
371 $result = ['encrypted' => true];
372 $key = random_bytes(256);
373 $iv = random_bytes(256);
374 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
376 // log the offending call so we can track it down
377 if (!openssl_public_encrypt($key, $k, $pubkey)) {
378 $x = debug_backtrace();
379 Logger::log('RSA failed. ' . print_r($x[0], true));
382 $result['alg'] = $alg;
383 $result['key'] = Strings::base64UrlEncode($k, true);
384 openssl_public_encrypt($iv, $i, $pubkey);
385 $result['iv'] = Strings::base64UrlEncode($i, true);
389 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
390 Hook::callAll('other_encapsulate', $x);
398 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
400 * @param string $data
401 * @param string $pubkey
406 private static function encapsulateAes($data, $pubkey)
409 Logger::log('aes_encapsulate: no key. data: ' . $data);
412 $key = random_bytes(32);
413 $iv = random_bytes(16);
414 $result = ['encrypted' => true];
415 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
417 // log the offending call so we can track it down
418 if (!openssl_public_encrypt($key, $k, $pubkey)) {
419 $x = debug_backtrace();
420 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
423 $result['alg'] = 'aes256cbc';
424 $result['key'] = Strings::base64UrlEncode($k, true);
425 openssl_public_encrypt($iv, $i, $pubkey);
426 $result['iv'] = Strings::base64UrlEncode($i, true);
433 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
435 * @param array $data ['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data]
436 * @param string $prvkey The private key used for decryption.
438 * @return string|boolean The decrypted string or false on failure.
441 public static function unencapsulate(array $data, $prvkey)
447 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
448 if ($alg === 'aes256cbc') {
449 return self::encapsulateAes($data['data'], $prvkey);
451 return self::encapsulateOther($data['data'], $prvkey, $alg);
456 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
459 * @param string $prvkey The private key used for decryption.
462 * @return string|boolean The decrypted string or false on failure.
463 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
465 private static function unencapsulateOther(array $data, $prvkey, $alg)
467 $fn = 'decrypt' . strtoupper($alg);
469 if (method_exists(__CLASS__, $fn)) {
470 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
471 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
473 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
475 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
476 Hook::callAll('other_unencapsulate', $x);
484 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
487 * @param string $prvkey The private key used for decryption.
489 * @return string|boolean The decrypted string or false on failure.
492 private static function unencapsulateAes($data, $prvkey)
494 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
495 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
497 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
502 * Creates cryptographic secure random digits
504 * @param string $digits The count of digits
505 * @return int The random Digits
507 * @throws \Exception In case 'random_int' isn't usable
509 public static function randomDigits($digits)
513 // generating cryptographically secure pseudo-random integers
514 for ($i = 0; $i < $digits; $i++) {
515 $rn .= random_int(0, 9);