aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/JSalmon.php
blob: 5531f791ffe6eaeb88f0edb85d7516f36fb375d2 (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
<?php

namespace Zotlabs\Lib;

use Zotlabs\Web\HTTPSig;

class JSalmon {

	static function sign($data,$key_id,$key,$data_type = 'application/x-zot+json') {

		$data      = base64url_encode(json_encode($data,true),true); // strip padding
		$encoding  = 'base64url';
		$algorithm = 'RSA-SHA256';

		$data = preg_replace('/\s+/','',$data);

		// precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods

		$precomputed = '.' . base64url_encode($data_type,true) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng';

		$signature  = base64url_encode(Crypto::sign($data . $precomputed, $key), true);

		return ([
			'signed'    => true,
			'data'      => $data,
			'data_type' => $data_type,
			'encoding'  => $encoding,
			'alg'       => $algorithm,
			'sigs'      => [
				'value'  => $signature,
				'key_id' => base64url_encode($key_id, true)
			]
		]);

	}

	static function verify($x) {

		logger('verify');
		$ret = [ 'results' => [] ];

		if(! is_array($x)) {
			return false;
		}
		if(! ( array_key_exists('signed',$x) && $x['signed'])) {
			return false;
		}

		$signed_data = preg_replace('/\s+/','',$x['data']) . '.'
			. base64url_encode($x['data_type'],true) . '.'
			. base64url_encode($x['encoding'],true) . '.'
			. base64url_encode($x['alg'],true);

		$key = HTTPSig::get_key(EMPTY_STR,'zot6',base64url_decode($x['sigs']['key_id']));
		logger('key: ' . print_r($key,true), LOGGER_DATA);
		if($key['portable_id'] && $key['public_key']) {
			if(Crypto::verify($signed_data,base64url_decode($x['sigs']['value']),$key['public_key'])) {
				logger('verified');
				$ret = [ 'success' => true, 'signer' => $key['portable_id'], 'hubloc' => $key['hubloc'] ];
			}
		}

		return $ret;

	}

	static function unpack($data) {
		return json_decode(base64url_decode($data),true);
	}


}