3 * @file src/Util/Crypto.php
5 namespace Friendica\Util;
7 use Friendica\Core\Config;
8 use Friendica\Core\Hook;
9 use Friendica\Core\Logger;
18 // supported algorithms are 'sha256', 'sha1'
20 * @param string $data data
21 * @param string $key key
22 * @param string $alg algorithm
25 public static function rsaSign($data, $key, $alg = 'sha256')
27 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
32 * @param string $data data
33 * @param string $sig signature
34 * @param string $key key
35 * @param string $alg algorithm
38 public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
40 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
44 * @param string $Der der formatted string
45 * @param string $Private key type optional, default false
48 private static function DerToPem($Der, $Private = false)
51 $Der = base64_encode($Der);
53 $lines = str_split($Der, 65);
54 $body = implode("\n", $lines);
56 $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
58 $result = "-----BEGIN {$title}-----\n";
59 $result .= $body . "\n";
60 $result .= "-----END {$title}-----\n";
66 * @param string $Der der formatted string
69 private static function DerToRsa($Der)
72 $Der = base64_encode($Der);
74 $lines = str_split($Der, 64);
75 $body = implode("\n", $lines);
77 $title = 'RSA PUBLIC KEY';
79 $result = "-----BEGIN {$title}-----\n";
80 $result .= $body . "\n";
81 $result .= "-----END {$title}-----\n";
87 * @param string $Modulus modulo
88 * @param string $PublicExponent exponent
91 private static function pkcs8Encode($Modulus, $PublicExponent)
94 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
95 $modulus->SetIntBuffer($Modulus);
96 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
97 $publicExponent->SetIntBuffer($PublicExponent);
98 $keySequenceItems = [$modulus, $publicExponent];
99 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
100 $keySequence->SetSequence($keySequenceItems);
102 $bitStringValue = $keySequence->Encode();
103 $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
104 $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
105 $bitString->Value = $bitStringValue;
107 $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
108 $body = new ASNValue(ASNValue::TAG_SEQUENCE);
109 $body->Value = $bodyValue;
110 //Get DER encoded public key:
111 $PublicDER = $body->Encode();
116 * @param string $Modulus modulo
117 * @param string $PublicExponent exponent
120 private static function pkcs1Encode($Modulus, $PublicExponent)
122 //Encode key sequence
123 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
124 $modulus->SetIntBuffer($Modulus);
125 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
126 $publicExponent->SetIntBuffer($PublicExponent);
127 $keySequenceItems = [$modulus, $publicExponent];
128 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
129 $keySequence->SetSequence($keySequenceItems);
131 $bitStringValue = $keySequence->Encode();
132 return $bitStringValue;
136 * @param string $m modulo
137 * @param string $e exponent
140 public static function meToPem($m, $e)
142 $der = self::pkcs8Encode($m, $e);
143 $key = self::DerToPem($der, false);
148 * @param string $key key
149 * @param string $m modulo reference
150 * @param object $e exponent reference
153 private static function pubRsaToMe($key, &$m, &$e)
155 $lines = explode("\n", $key);
157 unset($lines[count($lines)]);
158 $x = base64_decode(implode('', $lines));
160 $r = ASN_BASE::parseASNString($x);
162 $m = Strings::base64UrlDecode($r[0]->asnData[0]->asnData);
163 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData);
167 * @param string $key key
170 public static function rsaToPem($key)
172 self::pubRsaToMe($key, $m, $e);
173 return self::meToPem($m, $e);
177 * @param string $key key
180 private static function pemToRsa($key)
182 self::pemToMe($key, $m, $e);
183 return self::meToRsa($m, $e);
187 * @param string $key key
188 * @param string $m modulo reference
189 * @param string $e exponent reference
192 public static function pemToMe($key, &$m, &$e)
194 $lines = explode("\n", $key);
196 unset($lines[count($lines)]);
197 $x = base64_decode(implode('', $lines));
199 $r = ASN_BASE::parseASNString($x);
201 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
202 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
206 * @param string $m modulo
207 * @param string $e exponent
210 private static function meToRsa($m, $e)
212 $der = self::pkcs1Encode($m, $e);
213 $key = self::DerToRsa($der);
218 * @param integer $bits number of bits
221 public static function newKeypair($bits)
224 'digest_alg' => 'sha1',
225 'private_key_bits' => $bits,
226 'encrypt_key' => false
229 $conf = Config::get('system', 'openssl_conf_file');
231 $openssl_options['config'] = $conf;
233 $result = openssl_pkey_new($openssl_options);
235 if (empty($result)) {
236 Logger::log('new_keypair: failed');
241 $response = ['prvkey' => '', 'pubkey' => ''];
243 openssl_pkey_export($result, $response['prvkey']);
246 $pkey = openssl_pkey_get_details($result);
247 $response['pubkey'] = $pkey["key"];
253 * Encrypt a string with 'aes-256-cbc' cipher method.
255 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
257 * @param string $data
258 * @param string $key The key used for encryption.
259 * @param string $iv A non-NULL Initialization Vector.
261 * @return string|boolean Encrypted string or false on failure.
263 private static function encryptAES256CBC($data, $key, $iv)
265 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
269 * Decrypt a string with 'aes-256-cbc' cipher method.
271 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
273 * @param string $data
274 * @param string $key The key used for decryption.
275 * @param string $iv A non-NULL Initialization Vector.
277 * @return string|boolean Decrypted string or false on failure.
279 private static function decryptAES256CBC($data, $key, $iv)
281 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
285 * Encrypt a string with 'aes-256-ctr' cipher method.
287 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
289 * @param string $data
290 * @param string $key The key used for encryption.
291 * @param string $iv A non-NULL Initialization Vector.
293 * @return string|boolean Encrypted string or false on failure.
295 private static function encryptAES256CTR($data, $key, $iv)
297 $key = substr($key, 0, 32);
298 $iv = substr($iv, 0, 16);
299 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
303 * Decrypt a string with 'aes-256-ctr' cipher method.
305 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
307 * @param string $data
308 * @param string $key The key used for decryption.
309 * @param string $iv A non-NULL Initialization Vector.
311 * @return string|boolean Decrypted string or false on failure.
313 private static function decryptAES256CTR($data, $key, $iv)
315 $key = substr($key, 0, 32);
316 $iv = substr($iv, 0, 16);
317 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
322 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
324 * @param string $data
325 * @param string $pubkey The public key.
326 * @param string $alg The algorithm used for encryption.
330 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
332 if ($alg === 'aes256cbc') {
333 return self::encapsulateAes($data, $pubkey);
335 return self::encapsulateOther($data, $pubkey, $alg);
340 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
343 * @param type $pubkey The public key.
344 * @param type $alg The algorithm used for encryption.
348 private static function encapsulateOther($data, $pubkey, $alg)
351 Logger::log('no key. data: '.$data);
353 $fn = 'encrypt' . strtoupper($alg);
354 if (method_exists(__CLASS__, $fn)) {
355 $result = ['encrypted' => true];
356 $key = random_bytes(256);
357 $iv = random_bytes(256);
358 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
360 // log the offending call so we can track it down
361 if (!openssl_public_encrypt($key, $k, $pubkey)) {
362 $x = debug_backtrace();
363 Logger::log('RSA failed. ' . print_r($x[0], true));
366 $result['alg'] = $alg;
367 $result['key'] = Strings::base64UrlEncode($k, true);
368 openssl_public_encrypt($iv, $i, $pubkey);
369 $result['iv'] = Strings::base64UrlEncode($i, true);
373 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
374 Hook::callAll('other_encapsulate', $x);
382 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
384 * @param string $data
385 * @param string $pubkey
389 private static function encapsulateAes($data, $pubkey)
392 Logger::log('aes_encapsulate: no key. data: ' . $data);
395 $key = random_bytes(32);
396 $iv = random_bytes(16);
397 $result = ['encrypted' => true];
398 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
400 // log the offending call so we can track it down
401 if (!openssl_public_encrypt($key, $k, $pubkey)) {
402 $x = debug_backtrace();
403 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
406 $result['alg'] = 'aes256cbc';
407 $result['key'] = Strings::base64UrlEncode($k, true);
408 openssl_public_encrypt($iv, $i, $pubkey);
409 $result['iv'] = Strings::base64UrlEncode($i, true);
416 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
418 * @param string $data
419 * @param string $prvkey The private key used for decryption.
421 * @return string|boolean The decrypted string or false on failure.
423 public static function unencapsulate($data, $prvkey)
429 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
430 if ($alg === 'aes256cbc') {
431 return self::encapsulateAes($data, $prvkey);
433 return self::encapsulateOther($data, $prvkey, $alg);
438 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
440 * @param string $data
441 * @param string $prvkey The private key used for decryption.
444 * @return string|boolean The decrypted string or false on failure.
446 private static function unencapsulateOther($data, $prvkey, $alg)
448 $fn = 'decrypt' . strtoupper($alg);
450 if (method_exists(__CLASS__, $fn)) {
451 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
452 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
454 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
456 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
457 Hook::callAll('other_unencapsulate', $x);
465 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
468 * @param string $prvkey The private key used for decryption.
470 * @return string|boolean The decrypted string or false on failure.
472 private static function unencapsulateAes($data, $prvkey)
474 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
475 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
477 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
482 * Creates cryptographic secure random digits
484 * @param string $digits The count of digits
485 * @return int The random Digits
487 * @throws \Exception In case 'random_int' isn't usable
489 public static function randomDigits($digits)
493 // generating cryptographically secure pseudo-random integers
494 for ($i = 0; $i < $digits; $i++) {
495 $rn .= random_int(0, 9);