3 * @file src/Util/Crypto.php
5 namespace Friendica\Util;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\Logger;
10 use Friendica\Util\Strings;
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')
28 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
33 * @param string $data data
34 * @param string $sig signature
35 * @param string $key key
36 * @param string $alg algorithm
39 public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
41 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
45 * @param string $Der der formatted string
46 * @param string $Private key type optional, default false
49 private static function DerToPem($Der, $Private = false)
52 $Der = base64_encode($Der);
54 $lines = str_split($Der, 65);
55 $body = implode("\n", $lines);
57 $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
59 $result = "-----BEGIN {$title}-----\n";
60 $result .= $body . "\n";
61 $result .= "-----END {$title}-----\n";
67 * @param string $Der der formatted string
70 private static function DerToRsa($Der)
73 $Der = base64_encode($Der);
75 $lines = str_split($Der, 64);
76 $body = implode("\n", $lines);
78 $title = 'RSA PUBLIC KEY';
80 $result = "-----BEGIN {$title}-----\n";
81 $result .= $body . "\n";
82 $result .= "-----END {$title}-----\n";
88 * @param string $Modulus modulo
89 * @param string $PublicExponent exponent
92 private static function pkcs8Encode($Modulus, $PublicExponent)
95 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
96 $modulus->SetIntBuffer($Modulus);
97 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
98 $publicExponent->SetIntBuffer($PublicExponent);
99 $keySequenceItems = [$modulus, $publicExponent];
100 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
101 $keySequence->SetSequence($keySequenceItems);
103 $bitStringValue = $keySequence->Encode();
104 $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
105 $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
106 $bitString->Value = $bitStringValue;
108 $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
109 $body = new ASNValue(ASNValue::TAG_SEQUENCE);
110 $body->Value = $bodyValue;
111 //Get DER encoded public key:
112 $PublicDER = $body->Encode();
117 * @param string $Modulus modulo
118 * @param string $PublicExponent exponent
121 private static function pkcs1Encode($Modulus, $PublicExponent)
123 //Encode key sequence
124 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
125 $modulus->SetIntBuffer($Modulus);
126 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
127 $publicExponent->SetIntBuffer($PublicExponent);
128 $keySequenceItems = [$modulus, $publicExponent];
129 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
130 $keySequence->SetSequence($keySequenceItems);
132 $bitStringValue = $keySequence->Encode();
133 return $bitStringValue;
137 * @param string $m modulo
138 * @param string $e exponent
141 public static function meToPem($m, $e)
143 $der = self::pkcs8Encode($m, $e);
144 $key = self::DerToPem($der, false);
149 * @param string $key key
150 * @param string $m modulo reference
151 * @param object $e exponent reference
154 private static function pubRsaToMe($key, &$m, &$e)
156 $lines = explode("\n", $key);
158 unset($lines[count($lines)]);
159 $x = base64_decode(implode('', $lines));
161 $r = ASN_BASE::parseASNString($x);
163 $m = Strings::base64UrlDecode($r[0]->asnData[0]->asnData);
164 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData);
168 * @param string $key key
171 public static function rsaToPem($key)
173 self::pubRsaToMe($key, $m, $e);
174 return self::meToPem($m, $e);
178 * @param string $key key
181 private static function pemToRsa($key)
183 self::pemToMe($key, $m, $e);
184 return self::meToRsa($m, $e);
188 * @param string $key key
189 * @param string $m modulo reference
190 * @param string $e exponent reference
193 public static function pemToMe($key, &$m, &$e)
195 $lines = explode("\n", $key);
197 unset($lines[count($lines)]);
198 $x = base64_decode(implode('', $lines));
200 $r = ASN_BASE::parseASNString($x);
202 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
203 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
207 * @param string $m modulo
208 * @param string $e exponent
211 private static function meToRsa($m, $e)
213 $der = self::pkcs1Encode($m, $e);
214 $key = self::DerToRsa($der);
219 * @param integer $bits number of bits
222 public static function newKeypair($bits)
225 'digest_alg' => 'sha1',
226 'private_key_bits' => $bits,
227 'encrypt_key' => false
230 $conf = Config::get('system', 'openssl_conf_file');
232 $openssl_options['config'] = $conf;
234 $result = openssl_pkey_new($openssl_options);
236 if (empty($result)) {
237 Logger::log('new_keypair: failed');
242 $response = ['prvkey' => '', 'pubkey' => ''];
244 openssl_pkey_export($result, $response['prvkey']);
247 $pkey = openssl_pkey_get_details($result);
248 $response['pubkey'] = $pkey["key"];
254 * Encrypt a string with 'aes-256-cbc' cipher method.
256 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
258 * @param string $data
259 * @param string $key The key used for encryption.
260 * @param string $iv A non-NULL Initialization Vector.
262 * @return string|boolean Encrypted string or false on failure.
264 private static function encryptAES256CBC($data, $key, $iv)
266 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
270 * Decrypt a string with 'aes-256-cbc' cipher method.
272 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
274 * @param string $data
275 * @param string $key The key used for decryption.
276 * @param string $iv A non-NULL Initialization Vector.
278 * @return string|boolean Decrypted string or false on failure.
280 private static function decryptAES256CBC($data, $key, $iv)
282 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
286 * Encrypt a string with 'aes-256-ctr' cipher method.
288 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
290 * @param string $data
291 * @param string $key The key used for encryption.
292 * @param string $iv A non-NULL Initialization Vector.
294 * @return string|boolean Encrypted string or false on failure.
296 private static function encryptAES256CTR($data, $key, $iv)
298 $key = substr($key, 0, 32);
299 $iv = substr($iv, 0, 16);
300 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
304 * Decrypt a string with 'aes-256-ctr' cipher method.
306 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
308 * @param string $data
309 * @param string $key The key used for decryption.
310 * @param string $iv A non-NULL Initialization Vector.
312 * @return string|boolean Decrypted string or false on failure.
314 private static function decryptAES256CTR($data, $key, $iv)
316 $key = substr($key, 0, 32);
317 $iv = substr($iv, 0, 16);
318 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
323 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
325 * @param string $data
326 * @param string $pubkey The public key.
327 * @param string $alg The algorithm used for encryption.
331 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
333 if ($alg === 'aes256cbc') {
334 return self::encapsulateAes($data, $pubkey);
336 return self::encapsulateOther($data, $pubkey, $alg);
341 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
344 * @param type $pubkey The public key.
345 * @param type $alg The algorithm used for encryption.
349 private static function encapsulateOther($data, $pubkey, $alg)
352 Logger::log('no key. data: '.$data);
354 $fn = 'encrypt' . strtoupper($alg);
355 if (method_exists(__CLASS__, $fn)) {
356 $result = ['encrypted' => true];
357 $key = random_bytes(256);
358 $iv = random_bytes(256);
359 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
361 // log the offending call so we can track it down
362 if (!openssl_public_encrypt($key, $k, $pubkey)) {
363 $x = debug_backtrace();
364 Logger::log('RSA failed. ' . print_r($x[0], true));
367 $result['alg'] = $alg;
368 $result['key'] = Strings::base64UrlEncode($k, true);
369 openssl_public_encrypt($iv, $i, $pubkey);
370 $result['iv'] = Strings::base64UrlEncode($i, true);
374 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
375 Addon::callHooks('other_encapsulate', $x);
383 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
385 * @param string $data
386 * @param string $pubkey
390 private static function encapsulateAes($data, $pubkey)
393 Logger::log('aes_encapsulate: no key. data: ' . $data);
396 $key = random_bytes(32);
397 $iv = random_bytes(16);
398 $result = ['encrypted' => true];
399 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
401 // log the offending call so we can track it down
402 if (!openssl_public_encrypt($key, $k, $pubkey)) {
403 $x = debug_backtrace();
404 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
407 $result['alg'] = 'aes256cbc';
408 $result['key'] = Strings::base64UrlEncode($k, true);
409 openssl_public_encrypt($iv, $i, $pubkey);
410 $result['iv'] = Strings::base64UrlEncode($i, true);
417 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
419 * @param string $data
420 * @param string $prvkey The private key used for decryption.
422 * @return string|boolean The decrypted string or false on failure.
424 public static function unencapsulate($data, $prvkey)
430 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
431 if ($alg === 'aes256cbc') {
432 return self::encapsulateAes($data, $prvkey);
434 return self::encapsulateOther($data, $prvkey, $alg);
439 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
441 * @param string $data
442 * @param string $prvkey The private key used for decryption.
445 * @return string|boolean The decrypted string or false on failure.
447 private static function unencapsulateOther($data, $prvkey, $alg)
449 $fn = 'decrypt' . strtoupper($alg);
451 if (method_exists(__CLASS__, $fn)) {
452 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
453 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
455 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
457 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
458 Addon::callHooks('other_unencapsulate', $x);
466 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
469 * @param string $prvkey The private key used for decryption.
471 * @return string|boolean The decrypted string or false on failure.
473 private static function unencapsulateAes($data, $prvkey)
475 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
476 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
478 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
483 * Creates cryptographic secure random digits
485 * @param string $digits The count of digits
486 * @return int The random Digits
488 * @throws \Exception In case 'random_int' isn't usable
490 public static function randomDigits($digits)
494 // generating cryptographically secure pseudo-random integers
495 for ($i = 0; $i < $digits; $i++) {
496 $rn .= random_int(0, 9);