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/>.
20 * This is in the same namespace as Crypto for mocking 'rand' and 'random_init'
23 /// @todo Use right namespace - needs alternative way of mocking random_int()
24 namespace Friendica\Util;
26 use phpseclib\Crypt\RSA;
27 use phpseclib\Math\BigInteger;
28 use PHPUnit\Framework\TestCase;
30 class CryptoTest extends TestCase
33 * Replaces random_int results with given mocks
36 private function assertRandomInt($min, $max)
39 $phpMock['random_int'] = function ($mMin, $mMax) use ($min, $max) {
40 self::assertEquals($min, $mMin);
41 self::assertEquals($max, $mMax);
46 public function testRandomDigitsRandomInt()
48 self::assertRandomInt(0, 9);
50 $test = Crypto::randomDigits(1);
51 self::assertEquals(1, strlen($test));
52 self::assertEquals(1, $test);
54 $test = Crypto::randomDigits(8);
55 self::assertEquals(8, strlen($test));
56 self::assertEquals(11111111, $test);
59 public function dataRsa()
63 'key' => file_get_contents(__DIR__ . '/../../datasets/crypto/rsa/diaspora-public-rsa-base64'),
64 'expected' => file_get_contents(__DIR__ . '/../../datasets/crypto/rsa/diaspora-public-pem'),
70 * @dataProvider dataRsa
72 public function testPubRsaToMe(string $key, string $expected)
74 self::assertEquals($expected, Crypto::rsaToPem(base64_decode($key)));
78 public function dataPEM()
82 'key' => file_get_contents(__DIR__ . '/../../datasets/crypto/rsa/diaspora-public-pem'),
88 * @dataProvider dataPEM
90 public function testPemToMe(string $key)
92 Crypto::pemToMe($key, $m, $e);
94 $expectedRSA = new RSA();
95 $expectedRSA->loadKey([
96 'e' => new BigInteger($e, 256),
97 'n' => new BigInteger($m, 256)
100 self::assertEquals($expectedRSA->getPublicKey(), $key);
104 * @dataProvider dataPEM
106 public function testMeToPem(string $key)
108 Crypto::pemToMe($key, $m, $e);
110 $checkKey = Crypto::meToPem($m, $e);
112 self::assertEquals($key, $checkKey);
117 * A workaround to replace the PHP native random_int() (>= 7.0) with a mocked function
121 function random_int($min, $max)
124 if (isset($phpMock['random_int'])) {
125 return call_user_func_array($phpMock['random_int'], func_get_args());