aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/JcsEddsa2022.php
blob: 425627b623f2515b3a5ce734f2b7bdc3c4673d48 (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
<?php

namespace Zotlabs\Lib;

use Mmccook\JsonCanonicalizator\JsonCanonicalizatorFactory;
use StephenHill\Base58;

class JcsEddsa2022 {

	public  function  __construct() {
		return $this;
	}

	public function sign($data, $channel): array {
		$base58 = new Base58();
		$pubkey = (new Multibase())->publicKey($channel['channel_epubkey']);
		$options = [
			'type' => 'DataIntegrityProof',
			'cryptosuite' => 'eddsa-jcs-2022',
			'created' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
			'verificationMethod' => channel_url($channel) . '#' . $pubkey,
			'proofPurpose' => 'assertionMethod',
		];

		$optionsHash = $this->hash($this->signableOptions($options), true);
		$dataHash = $this->hash($this->signableData($data), true);

		$options['proofValue'] = 'z' . $base58->encode(sodium_crypto_sign_detached($optionsHash . $dataHash,
				sodium_base642bin($channel['channel_eprvkey'], SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING)));

		return $options;
	}

	public function verify($data, $publicKey) {
		$base58 = new Base58();
		$encodedSignature = $data['proof']['proofValue'] ?? '';
		if (!str_starts_with($encodedSignature,'z')) {
			return false;
		}
		$encodedSignature = substr($encodedSignature, 1);
		$optionsHash = $this->hash($this->signableOptions($data['proof']), true);
		$dataHash = $this->hash($this->signableData($data),true);

		try {
			$result = sodium_crypto_sign_verify_detached($base58->decode($encodedSignature), $optionsHash . $dataHash,
				(new Multibase())->decode($publicKey, true));
		}
		catch (\Exception $e) {
			logger('verify exception:' .  $e->getMessage());
		}

		logger('SignatureVerify (eddsa-jcs-2022) ' . (($result) ? 'true' : 'false'));

		return $result;
	}

	public function signableData($data) {
		$signableData = [];
		if ($data) {
			foreach ($data as $k => $v) {
				if ($k != 'proof') {
					$signableData[$k] = $v;
				}
			}
		}
		return $signableData;
	}

	public function signableOptions($options) {
		$signableOptions = [];

		if ($options) {
			foreach ($options as $k => $v) {
				if ($k !== 'proofValue') {
					$signableOptions[$k] = $v;
				}
			}
		}
		return $signableOptions;
	}

	public function hash($obj, $binary = false) {
		return hash('sha256', $this->canonicalize($obj), $binary);
	}

	public function canonicalize($data) {
		$canonicalization = JsonCanonicalizatorFactory::getInstance();
		return $canonicalization->canonicalize($data);
	}

}