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 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)
77 'e' => new BigInteger($e, 256),
78 'n' => new BigInteger($m, 256)
80 return $rsa->getPublicKey();
84 * Transform RSA public keys to standard PEM output
86 * @param string $key A RSA public key
88 * @return string The PEM output of this key
90 public static function rsaToPem(string $key)
93 $rsa->setPublicKey($key);
95 return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS8);
99 * Extracts the modulo and exponent reference from a public PEM key
101 * @param string $key public PEM key
102 * @param string $modulus (ref) modulo reference
103 * @param string $exponent (ref) exponent reference
107 public static function pemToMe(string $key, &$modulus, &$exponent)
111 $rsa->setPublicKey();
113 $modulus = $rsa->modulus->toBytes();
114 $exponent = $rsa->exponent->toBytes();
118 * @param integer $bits number of bits
120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
122 public static function newKeypair($bits)
125 'digest_alg' => 'sha1',
126 'private_key_bits' => $bits,
127 'encrypt_key' => false
130 $conf = DI::config()->get('system', 'openssl_conf_file');
132 $openssl_options['config'] = $conf;
134 $result = openssl_pkey_new($openssl_options);
136 if (empty($result)) {
137 Logger::log('new_keypair: failed');
142 $response = ['prvkey' => '', 'pubkey' => ''];
144 openssl_pkey_export($result, $response['prvkey']);
147 $pkey = openssl_pkey_get_details($result);
148 $response['pubkey'] = $pkey["key"];
154 * Encrypt a string with 'aes-256-cbc' cipher method.
156 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
158 * @param string $data
159 * @param string $key The key used for encryption.
160 * @param string $iv A non-NULL Initialization Vector.
162 * @return string|boolean Encrypted string or false on failure.
164 private static function encryptAES256CBC($data, $key, $iv)
166 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
170 * Decrypt a string with 'aes-256-cbc' cipher method.
172 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
174 * @param string $data
175 * @param string $key The key used for decryption.
176 * @param string $iv A non-NULL Initialization Vector.
178 * @return string|boolean Decrypted string or false on failure.
180 private static function decryptAES256CBC($data, $key, $iv)
182 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
187 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
189 * @param string $data
190 * @param string $pubkey The public key.
191 * @param string $alg The algorithm used for encryption.
196 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
198 if ($alg === 'aes256cbc') {
199 return self::encapsulateAes($data, $pubkey);
201 return self::encapsulateOther($data, $pubkey, $alg);
206 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
208 * @param string $data
209 * @param string $pubkey The public key.
210 * @param string $alg The algorithm used for encryption.
215 private static function encapsulateOther($data, $pubkey, $alg)
218 Logger::log('no key. data: '.$data);
220 $fn = 'encrypt' . strtoupper($alg);
221 if (method_exists(__CLASS__, $fn)) {
222 $result = ['encrypted' => true];
223 $key = random_bytes(256);
224 $iv = random_bytes(256);
225 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
227 // log the offending call so we can track it down
228 if (!openssl_public_encrypt($key, $k, $pubkey)) {
229 $x = debug_backtrace();
230 Logger::notice('RSA failed', ['trace' => $x[0]]);
233 $result['alg'] = $alg;
234 $result['key'] = Strings::base64UrlEncode($k, true);
235 openssl_public_encrypt($iv, $i, $pubkey);
236 $result['iv'] = Strings::base64UrlEncode($i, true);
240 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
241 Hook::callAll('other_encapsulate', $x);
249 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
251 * @param string $data
252 * @param string $pubkey
257 private static function encapsulateAes($data, $pubkey)
260 Logger::log('aes_encapsulate: no key. data: ' . $data);
263 $key = random_bytes(32);
264 $iv = random_bytes(16);
265 $result = ['encrypted' => true];
266 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
268 // log the offending call so we can track it down
269 if (!openssl_public_encrypt($key, $k, $pubkey)) {
270 $x = debug_backtrace();
271 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
274 $result['alg'] = 'aes256cbc';
275 $result['key'] = Strings::base64UrlEncode($k, true);
276 openssl_public_encrypt($iv, $i, $pubkey);
277 $result['iv'] = Strings::base64UrlEncode($i, true);
284 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
286 * @param array $data ['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data]
287 * @param string $prvkey The private key used for decryption.
289 * @return string|boolean The decrypted string or false on failure.
292 public static function unencapsulate(array $data, $prvkey)
298 $alg = $data['alg'] ?? 'aes256cbc';
299 if ($alg === 'aes256cbc') {
300 return self::unencapsulateAes($data['data'], $prvkey);
303 return self::unencapsulateOther($data, $prvkey, $alg);
308 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
311 * @param string $prvkey The private key used for decryption.
314 * @return string|boolean The decrypted string or false on failure.
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
317 private static function unencapsulateOther(array $data, $prvkey, $alg)
319 $fn = 'decrypt' . strtoupper($alg);
321 if (method_exists(__CLASS__, $fn)) {
322 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
323 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
325 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
327 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
328 Hook::callAll('other_unencapsulate', $x);
336 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
339 * @param string $prvkey The private key used for decryption.
341 * @return string|boolean The decrypted string or false on failure.
344 private static function unencapsulateAes($data, $prvkey)
346 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
347 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
349 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
354 * Creates cryptographic secure random digits
356 * @param string $digits The count of digits
357 * @return int The random Digits
359 * @throws \Exception In case 'random_int' isn't usable
361 public static function randomDigits($digits)
365 // generating cryptographically secure pseudo-random integers
366 for ($i = 0; $i < $digits; $i++) {
367 $rn .= random_int(0, 9);