3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
28 use ParagonIE\ConstantTime\Base64UrlSafe;
29 use phpseclib\Crypt\RSA;
30 use phpseclib\Math\BigInteger;
37 // supported algorithms are 'sha256', 'sha1'
39 * @param string $data data
40 * @param string $key key
41 * @param string $alg algorithm
44 public static function rsaSign($data, $key, $alg = 'sha256')
47 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
49 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
54 * @param string $data data
55 * @param string $sig signature
56 * @param string $key key
57 * @param string $alg algorithm
60 public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
63 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
65 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
70 * @param string $m modulo
71 * @param string $e exponent
74 public static function meToPem($m, $e)
78 'e' => new BigInteger($e, 256),
79 'n' => new BigInteger($m, 256)
81 return $rsa->getPublicKey();
85 * Transform RSA public keys to standard PEM output
87 * @param string $key A RSA public key
89 * @return string The PEM output of this key
91 public static function rsaToPem(string $key)
94 $rsa->setPublicKey($key);
96 return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS8);
100 * Extracts the modulo and exponent reference from a public PEM key
102 * @param string $key public PEM key
103 * @param string $modulus (ref) modulo reference
104 * @param string $exponent (ref) exponent reference
108 public static function pemToMe(string $key, &$modulus, &$exponent)
112 $rsa->setPublicKey();
114 $modulus = $rsa->modulus->toBytes();
115 $exponent = $rsa->exponent->toBytes();
119 * @param integer $bits number of bits
121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
123 public static function newKeypair($bits)
126 'digest_alg' => 'sha1',
127 'private_key_bits' => $bits,
128 'encrypt_key' => false
131 $conf = DI::config()->get('system', 'openssl_conf_file');
133 $openssl_options['config'] = $conf;
135 $result = openssl_pkey_new($openssl_options);
137 if (empty($result)) {
138 Logger::log('new_keypair: failed');
143 $response = ['prvkey' => '', 'pubkey' => ''];
145 openssl_pkey_export($result, $response['prvkey']);
148 $pkey = openssl_pkey_get_details($result);
149 $response['pubkey'] = $pkey["key"];
155 * Create a new elliptic curve key pair
157 * @return array with the elements "prvkey", "vapid" and "pubkey"
159 public static function newECKeypair()
162 'curve_name' => 'prime256v1',
163 'private_key_type' => OPENSSL_KEYTYPE_EC
166 $conf = DI::config()->get('system', 'openssl_conf_file');
168 $openssl_options['config'] = $conf;
170 $result = openssl_pkey_new($openssl_options);
172 if (empty($result)) {
173 Logger::notice('new_keypair: failed');
177 $response = ['prvkey' => '', 'pubkey' => '', 'vapid' => ''];
180 openssl_pkey_export($result, $response['prvkey']);
183 $pkey = openssl_pkey_get_details($result);
184 $response['pubkey'] = $pkey['key'];
187 // @see https://github.com/web-push-libs/web-push-php/blob/256a18b2a2411469c94943725fb6eccb9681bd75/src/Utils.php#L60-L62
189 $hexString .= str_pad(bin2hex($pkey['ec']['x']), 64, '0', STR_PAD_LEFT);
190 $hexString .= str_pad(bin2hex($pkey['ec']['y']), 64, '0', STR_PAD_LEFT);
191 $response['vapid'] = Base64UrlSafe::encode(hex2bin($hexString));
197 * Encrypt a string with 'aes-256-cbc' cipher method.
199 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
201 * @param string $data
202 * @param string $key The key used for encryption.
203 * @param string $iv A non-NULL Initialization Vector.
205 * @return string|boolean Encrypted string or false on failure.
207 private static function encryptAES256CBC($data, $key, $iv)
209 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
213 * Decrypt a string with 'aes-256-cbc' cipher method.
215 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
217 * @param string $data
218 * @param string $key The key used for decryption.
219 * @param string $iv A non-NULL Initialization Vector.
221 * @return string|boolean Decrypted string or false on failure.
223 private static function decryptAES256CBC($data, $key, $iv)
225 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
230 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
232 * @param string $data
233 * @param string $pubkey The public key.
234 * @param string $alg The algorithm used for encryption.
239 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
241 if ($alg === 'aes256cbc') {
242 return self::encapsulateAes($data, $pubkey);
244 return self::encapsulateOther($data, $pubkey, $alg);
249 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
251 * @param string $data
252 * @param string $pubkey The public key.
253 * @param string $alg The algorithm used for encryption.
258 private static function encapsulateOther($data, $pubkey, $alg)
261 Logger::log('no key. data: '.$data);
263 $fn = 'encrypt' . strtoupper($alg);
264 if (method_exists(__CLASS__, $fn)) {
265 $result = ['encrypted' => true];
266 $key = random_bytes(256);
267 $iv = random_bytes(256);
268 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
270 // log the offending call so we can track it down
271 if (!openssl_public_encrypt($key, $k, $pubkey)) {
272 $x = debug_backtrace();
273 Logger::notice('RSA failed', ['trace' => $x[0]]);
276 $result['alg'] = $alg;
277 $result['key'] = Strings::base64UrlEncode($k, true);
278 openssl_public_encrypt($iv, $i, $pubkey);
279 $result['iv'] = Strings::base64UrlEncode($i, true);
283 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
284 Hook::callAll('other_encapsulate', $x);
292 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
294 * @param string $data
295 * @param string $pubkey
300 private static function encapsulateAes($data, $pubkey)
303 Logger::log('aes_encapsulate: no key. data: ' . $data);
306 $key = random_bytes(32);
307 $iv = random_bytes(16);
308 $result = ['encrypted' => true];
309 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
311 // log the offending call so we can track it down
312 if (!openssl_public_encrypt($key, $k, $pubkey)) {
313 $x = debug_backtrace();
314 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
317 $result['alg'] = 'aes256cbc';
318 $result['key'] = Strings::base64UrlEncode($k, true);
319 openssl_public_encrypt($iv, $i, $pubkey);
320 $result['iv'] = Strings::base64UrlEncode($i, true);
327 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
329 * @param array $data ['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data]
330 * @param string $prvkey The private key used for decryption.
332 * @return string|boolean The decrypted string or false on failure.
335 public static function unencapsulate(array $data, $prvkey)
341 $alg = $data['alg'] ?? 'aes256cbc';
342 if ($alg === 'aes256cbc') {
343 return self::unencapsulateAes($data['data'], $prvkey);
346 return self::unencapsulateOther($data, $prvkey, $alg);
351 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
354 * @param string $prvkey The private key used for decryption.
357 * @return string|boolean The decrypted string or false on failure.
358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360 private static function unencapsulateOther(array $data, $prvkey, $alg)
362 $fn = 'decrypt' . strtoupper($alg);
364 if (method_exists(__CLASS__, $fn)) {
365 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
366 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
368 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
370 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
371 Hook::callAll('other_unencapsulate', $x);
379 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
382 * @param string $prvkey The private key used for decryption.
384 * @return string|boolean The decrypted string or false on failure.
387 private static function unencapsulateAes($data, $prvkey)
389 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
390 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
392 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
397 * Creates cryptographic secure random digits
399 * @param string $digits The count of digits
400 * @return int The random Digits
402 * @throws \Exception In case 'random_int' isn't usable
404 public static function randomDigits($digits)
408 // generating cryptographically secure pseudo-random integers
409 for ($i = 0; $i < $digits; $i++) {
410 $rn .= random_int(0, 9);