Line data Source code
1 : /*
2 : * Famedly Matrix SDK
3 : * Copyright (C) 2020, 2021 Famedly GmbH
4 : *
5 : * This program is free software: you can redistribute it and/or modify
6 : * it under the terms of the GNU Affero General Public License as
7 : * published by the Free Software Foundation, either version 3 of the
8 : * License, or (at your option) any later version.
9 : *
10 : * This program is distributed in the hope that it will be useful,
11 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 : * GNU Affero General Public License for more details.
14 : *
15 : * You should have received a copy of the GNU Affero General Public License
16 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 : */
18 :
19 : import 'package:canonical_json/canonical_json.dart';
20 : import 'package:olm/olm.dart' as olm;
21 :
22 : import 'package:matrix/matrix.dart';
23 :
24 : extension JsonSignatureCheckExtension on Map<String, dynamic> {
25 : /// Checks the signature of a signed json object.
26 10 : bool checkJsonSignature(String key, String userId, String deviceId) {
27 10 : final signatures = this['signatures'];
28 : if (signatures == null ||
29 10 : signatures is! Map<String, dynamic> ||
30 10 : !signatures.containsKey(userId)) {
31 : return false;
32 : }
33 10 : remove('unsigned');
34 10 : remove('signatures');
35 30 : if (!signatures[userId].containsKey('ed25519:$deviceId')) return false;
36 30 : final String signature = signatures[userId]['ed25519:$deviceId'];
37 10 : final canonical = canonicalJson.encode(this);
38 10 : final message = String.fromCharCodes(canonical);
39 : var isValid = false;
40 10 : final olmutil = olm.Utility();
41 : try {
42 10 : olmutil.ed25519_verify(key, message, signature);
43 : isValid = true;
44 : } catch (e, s) {
45 : isValid = false;
46 0 : Logs().w('[LibOlm] Signature check failed', e, s);
47 : } finally {
48 10 : olmutil.free();
49 : }
50 : return isValid;
51 : }
52 : }
|