aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/Keyutils.php
blob: 33f9102365b6bd5112c62d90788140a5558563e9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php

namespace Zotlabs\Lib;

use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Math\BigInteger;

/**
 * Keyutils
 * Convert RSA keys between various formats
 */
class Keyutils {

	/**
	 * @param string $m modulo
	 * @param string $e exponent
	 * @return string
	 */
	public static function meToPem(string $m, string $e): string
	{
		$parsedKey = PublicKeyLoader::load([
			'e' => new BigInteger($e, 256),
			'n' => new BigInteger($m, 256)
		]);
		if (method_exists($parsedKey, 'getPublicKey')) {
			$parsedKey = $parsedKey->getPublicKey();
		}
		return $parsedKey->toString('PKCS8');
	}

	/**
	 * @param string key
	 * @return string
	 */
    public static function rsaToPem(string $key): string
	{
		$parsedKey = PublicKeyLoader::load($key);
		if (method_exists($parsedKey, 'getPublicKey')) {
			$parsedKey = $parsedKey->getPublicKey();
		}
		return $parsedKey->toString('PKCS8');
	}

	/**
	 * @param string key
	 * @return string
	 */
	public static function pemToRsa(string $key): string
	{
		$parsedKey = PublicKeyLoader::load($key);
		if (method_exists($parsedKey, 'getPublicKey')) {
			$parsedKey = $parsedKey->getPublicKey();
		}
		return $parsedKey->toString('PKCS1');
	}

	/**
	 * @param string $key key
	 * @param string $m reference modulo
	 * @param string $e reference exponent
	 */
	public static function pemToMe(string $key): array
	{
		$parsedKey = PublicKeyLoader::load($key);
		if (method_exists($parsedKey, 'getPublicKey')) {
			$parsedKey = $parsedKey->getPublicKey();
		}
		$raw = $parsedKey->toString('Raw');

		$m = $raw['n'];
		$e = $raw['e'];

		return [$m->toBytes(), $e->toBytes()];
	}

	/**
	 * @param string $pubkey
	 * @return string
	 */
	public static function salmonKey(string $pubkey): string
	{
		[$m, $e] = self::pemToMe($pubkey);
		/** @noinspection PhpRedundantOptionalArgumentInspection */
		return 'RSA' . '.' . base64url_encode($m, true) . '.' . base64url_encode($e, true);
	}

	/**
	 * @param string $key
	 * @return string
	 */
	public static function convertSalmonKey(string $key): string
	{
		if (str_contains($key, ',')) {
			$rawkey = substr($key, strpos($key, ',') + 1);
		} else {
			$rawkey = substr($key, 5);
		}

		$key_info = explode('.', $rawkey);

		$m = base64url_decode($key_info[1]);
		$e = base64url_decode($key_info[2]);

		return self::meToPem($m, $e);
	}

}