aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/Keyutils.php
blob: 616ecfcf69b541da567ed4c7b57134fb792337a2 (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
<?php

namespace Zotlabs\Lib;

use phpseclib\Crypt\RSA;
use phpseclib\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($m, $e) {

		$rsa = new RSA();
		$rsa->loadKey([
			'e' => new BigInteger($e, 256),
			'n' => new BigInteger($m, 256)
		]);
		return $rsa->getPublicKey();

	}

	/**
	 * @param string key
	 * @return string
	 */
	public static function rsaToPem($key) {

		$rsa = new RSA();
		$rsa->setPublicKey($key);

		return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS8);

	}

	/**
	 * @param string key
	 * @return string
	 */
	public static function pemToRsa($key) {

		$rsa = new RSA();
		$rsa->setPublicKey($key);

		return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS1);

	}

	/**
	 * @param string $key key
	 * @param string $m reference modulo
	 * @param string $e reference exponent
	 */
	public static function pemToMe($key, &$m, &$e) {

		$rsa = new RSA();
		$rsa->loadKey($key);
		$rsa->setPublicKey();

		$m = $rsa->modulus->toBytes();
		$e = $rsa->exponent->toBytes();

	}

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

	/**
	 * @param string $key
	 * @return string
	 */
	public static function convertSalmonKey($key) {
		if (strstr($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);
	}

}