3 * @copyright Copyright (C) 2020, Friendica
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 phpseclib\Crypt\RSA;
29 use phpseclib\Math\BigInteger;
36 // supported algorithms are 'sha256', 'sha1'
38 * @param string $data data
39 * @param string $key key
40 * @param string $alg algorithm
43 public static function rsaSign($data, $key, $alg = 'sha256')
46 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
48 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
53 * @param string $data data
54 * @param string $sig signature
55 * @param string $key key
56 * @param string $alg algorithm
59 public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
62 Logger::warning('Empty key parameter', ['callstack' => System::callstack()]);
64 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
69 * @param string $m modulo
70 * @param string $e exponent
73 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 * Encrypt a string with 'aes-256-cbc' cipher method.
157 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
159 * @param string $data
160 * @param string $key The key used for encryption.
161 * @param string $iv A non-NULL Initialization Vector.
163 * @return string|boolean Encrypted string or false on failure.
165 private static function encryptAES256CBC($data, $key, $iv)
167 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
171 * Decrypt a string with 'aes-256-cbc' cipher method.
173 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
175 * @param string $data
176 * @param string $key The key used for decryption.
177 * @param string $iv A non-NULL Initialization Vector.
179 * @return string|boolean Decrypted string or false on failure.
181 private static function decryptAES256CBC($data, $key, $iv)
183 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
188 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
190 * @param string $data
191 * @param string $pubkey The public key.
192 * @param string $alg The algorithm used for encryption.
197 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
199 if ($alg === 'aes256cbc') {
200 return self::encapsulateAes($data, $pubkey);
202 return self::encapsulateOther($data, $pubkey, $alg);
207 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
209 * @param string $data
210 * @param string $pubkey The public key.
211 * @param string $alg The algorithm used for encryption.
216 private static function encapsulateOther($data, $pubkey, $alg)
219 Logger::log('no key. data: '.$data);
221 $fn = 'encrypt' . strtoupper($alg);
222 if (method_exists(__CLASS__, $fn)) {
223 $result = ['encrypted' => true];
224 $key = random_bytes(256);
225 $iv = random_bytes(256);
226 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
228 // log the offending call so we can track it down
229 if (!openssl_public_encrypt($key, $k, $pubkey)) {
230 $x = debug_backtrace();
231 Logger::notice('RSA failed', ['trace' => $x[0]]);
234 $result['alg'] = $alg;
235 $result['key'] = Strings::base64UrlEncode($k, true);
236 openssl_public_encrypt($iv, $i, $pubkey);
237 $result['iv'] = Strings::base64UrlEncode($i, true);
241 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
242 Hook::callAll('other_encapsulate', $x);
250 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
252 * @param string $data
253 * @param string $pubkey
258 private static function encapsulateAes($data, $pubkey)
261 Logger::log('aes_encapsulate: no key. data: ' . $data);
264 $key = random_bytes(32);
265 $iv = random_bytes(16);
266 $result = ['encrypted' => true];
267 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
269 // log the offending call so we can track it down
270 if (!openssl_public_encrypt($key, $k, $pubkey)) {
271 $x = debug_backtrace();
272 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
275 $result['alg'] = 'aes256cbc';
276 $result['key'] = Strings::base64UrlEncode($k, true);
277 openssl_public_encrypt($iv, $i, $pubkey);
278 $result['iv'] = Strings::base64UrlEncode($i, true);
285 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
287 * @param array $data ['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data]
288 * @param string $prvkey The private key used for decryption.
290 * @return string|boolean The decrypted string or false on failure.
293 public static function unencapsulate(array $data, $prvkey)
299 $alg = $data['alg'] ?? 'aes256cbc';
300 if ($alg === 'aes256cbc') {
301 return self::unencapsulateAes($data['data'], $prvkey);
304 return self::unencapsulateOther($data, $prvkey, $alg);
309 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
312 * @param string $prvkey The private key used for decryption.
315 * @return string|boolean The decrypted string or false on failure.
316 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318 private static function unencapsulateOther(array $data, $prvkey, $alg)
320 $fn = 'decrypt' . strtoupper($alg);
322 if (method_exists(__CLASS__, $fn)) {
323 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
324 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
326 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
328 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
329 Hook::callAll('other_unencapsulate', $x);
337 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
340 * @param string $prvkey The private key used for decryption.
342 * @return string|boolean The decrypted string or false on failure.
345 private static function unencapsulateAes($data, $prvkey)
347 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
348 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
350 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
355 * Creates cryptographic secure random digits
357 * @param string $digits The count of digits
358 * @return int The random Digits
360 * @throws \Exception In case 'random_int' isn't usable
362 public static function randomDigits($digits)
366 // generating cryptographically secure pseudo-random integers
367 for ($i = 0; $i < $digits; $i++) {
368 $rn .= random_int(0, 9);