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 bool $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
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
172 public static function rsaToPem($key)
174 self::pubRsaToMe($key, $m, $e);
175 return self::meToPem($m, $e);
179 * @param string $key key
183 private static function pemToRsa($key)
185 self::pemToMe($key, $m, $e);
186 return self::meToRsa($m, $e);
190 * @param string $key key
191 * @param string $m modulo reference
192 * @param string $e exponent reference
196 public static function pemToMe($key, &$m, &$e)
198 $lines = explode("\n", $key);
200 unset($lines[count($lines)]);
201 $x = base64_decode(implode('', $lines));
203 $r = ASN_BASE::parseASNString($x);
205 $m = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
206 $e = Strings::base64UrlDecode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
210 * @param string $m modulo
211 * @param string $e exponent
214 private static function meToRsa($m, $e)
216 $der = self::pkcs1Encode($m, $e);
217 $key = self::DerToRsa($der);
222 * @param integer $bits number of bits
224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
226 public static function newKeypair($bits)
229 'digest_alg' => 'sha1',
230 'private_key_bits' => $bits,
231 'encrypt_key' => false
234 $conf = Config::get('system', 'openssl_conf_file');
236 $openssl_options['config'] = $conf;
238 $result = openssl_pkey_new($openssl_options);
240 if (empty($result)) {
241 Logger::log('new_keypair: failed');
246 $response = ['prvkey' => '', 'pubkey' => ''];
248 openssl_pkey_export($result, $response['prvkey']);
251 $pkey = openssl_pkey_get_details($result);
252 $response['pubkey'] = $pkey["key"];
258 * Encrypt a string with 'aes-256-cbc' cipher method.
260 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
262 * @param string $data
263 * @param string $key The key used for encryption.
264 * @param string $iv A non-NULL Initialization Vector.
266 * @return string|boolean Encrypted string or false on failure.
268 private static function encryptAES256CBC($data, $key, $iv)
270 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
274 * Decrypt a string with 'aes-256-cbc' cipher method.
276 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
278 * @param string $data
279 * @param string $key The key used for decryption.
280 * @param string $iv A non-NULL Initialization Vector.
282 * @return string|boolean Decrypted string or false on failure.
284 private static function decryptAES256CBC($data, $key, $iv)
286 return openssl_decrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
290 * Encrypt a string with 'aes-256-ctr' cipher method.
292 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
294 * @param string $data
295 * @param string $key The key used for encryption.
296 * @param string $iv A non-NULL Initialization Vector.
298 * @return string|boolean Encrypted string or false on failure.
300 private static function encryptAES256CTR($data, $key, $iv)
302 $key = substr($key, 0, 32);
303 $iv = substr($iv, 0, 16);
304 return openssl_encrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
308 * Decrypt a string with 'aes-256-ctr' cipher method.
310 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
312 * @param string $data
313 * @param string $key The key used for decryption.
314 * @param string $iv A non-NULL Initialization Vector.
316 * @return string|boolean Decrypted string or false on failure.
318 private static function decryptAES256CTR($data, $key, $iv)
320 $key = substr($key, 0, 32);
321 $iv = substr($iv, 0, 16);
322 return openssl_decrypt($data, 'aes-256-ctr', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
327 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
329 * @param string $data
330 * @param string $pubkey The public key.
331 * @param string $alg The algorithm used for encryption.
336 public static function encapsulate($data, $pubkey, $alg = 'aes256cbc')
338 if ($alg === 'aes256cbc') {
339 return self::encapsulateAes($data, $pubkey);
341 return self::encapsulateOther($data, $pubkey, $alg);
346 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
348 * @param string $data
349 * @param string $pubkey The public key.
350 * @param string $alg The algorithm used for encryption.
355 private static function encapsulateOther($data, $pubkey, $alg)
358 Logger::log('no key. data: '.$data);
360 $fn = 'encrypt' . strtoupper($alg);
361 if (method_exists(__CLASS__, $fn)) {
362 $result = ['encrypted' => true];
363 $key = random_bytes(256);
364 $iv = random_bytes(256);
365 $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true);
367 // log the offending call so we can track it down
368 if (!openssl_public_encrypt($key, $k, $pubkey)) {
369 $x = debug_backtrace();
370 Logger::log('RSA failed. ' . print_r($x[0], true));
373 $result['alg'] = $alg;
374 $result['key'] = Strings::base64UrlEncode($k, true);
375 openssl_public_encrypt($iv, $i, $pubkey);
376 $result['iv'] = Strings::base64UrlEncode($i, true);
380 $x = ['data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data];
381 Hook::callAll('other_encapsulate', $x);
389 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
391 * @param string $data
392 * @param string $pubkey
397 private static function encapsulateAes($data, $pubkey)
400 Logger::log('aes_encapsulate: no key. data: ' . $data);
403 $key = random_bytes(32);
404 $iv = random_bytes(16);
405 $result = ['encrypted' => true];
406 $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true);
408 // log the offending call so we can track it down
409 if (!openssl_public_encrypt($key, $k, $pubkey)) {
410 $x = debug_backtrace();
411 Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
414 $result['alg'] = 'aes256cbc';
415 $result['key'] = Strings::base64UrlEncode($k, true);
416 openssl_public_encrypt($iv, $i, $pubkey);
417 $result['iv'] = Strings::base64UrlEncode($i, true);
424 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
426 * @param string $data
427 * @param string $prvkey The private key used for decryption.
429 * @return string|boolean The decrypted string or false on failure.
432 public static function unencapsulate($data, $prvkey)
438 $alg = ((array_key_exists('alg', $data)) ? $data['alg'] : 'aes256cbc');
439 if ($alg === 'aes256cbc') {
440 return self::encapsulateAes($data, $prvkey);
442 return self::encapsulateOther($data, $prvkey, $alg);
447 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
449 * @param string $data
450 * @param string $prvkey The private key used for decryption.
453 * @return string|boolean The decrypted string or false on failure.
454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
456 private static function unencapsulateOther($data, $prvkey, $alg)
458 $fn = 'decrypt' . strtoupper($alg);
460 if (method_exists(__CLASS__, $fn)) {
461 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
462 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
464 return self::$fn(Strings::base64UrlDecode($data['data']), $k, $i);
466 $x = ['data' => $data, 'prvkey' => $prvkey, 'alg' => $alg, 'result' => $data];
467 Hook::callAll('other_unencapsulate', $x);
475 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/crypto.php
478 * @param string $prvkey The private key used for decryption.
480 * @return string|boolean The decrypted string or false on failure.
483 private static function unencapsulateAes($data, $prvkey)
485 openssl_private_decrypt(Strings::base64UrlDecode($data['key']), $k, $prvkey);
486 openssl_private_decrypt(Strings::base64UrlDecode($data['iv']), $i, $prvkey);
488 return self::decryptAES256CBC(Strings::base64UrlDecode($data['data']), $k, $i);
493 * Creates cryptographic secure random digits
495 * @param string $digits The count of digits
496 * @return int The random Digits
498 * @throws \Exception In case 'random_int' isn't usable
500 public static function randomDigits($digits)
504 // generating cryptographically secure pseudo-random integers
505 for ($i = 0; $i < $digits; $i++) {
506 $rn .= random_int(0, 9);