Line data Source code
1 : /*
2 : * Famedly Matrix SDK
3 : * Copyright (C) 2019, 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 'dart:convert';
20 : import 'dart:typed_data';
21 :
22 : import 'package:vodozemac/vodozemac.dart';
23 :
24 : import 'package:matrix/encryption/utils/base64_unpadded.dart';
25 : import 'package:matrix/src/utils/crypto/crypto.dart';
26 :
27 : class EncryptedFile {
28 2 : EncryptedFile({
29 : required this.data,
30 : required this.k,
31 : required this.iv,
32 : required this.sha256,
33 : });
34 : Uint8List data;
35 : String k;
36 : String iv;
37 : String sha256;
38 : }
39 :
40 1 : Future<EncryptedFile> encryptFile(Uint8List input) async {
41 1 : final key = secureRandomBytes(32);
42 1 : final iv = secureRandomBytes(16);
43 1 : final data = CryptoUtils.aesCtr(input: input, key: key, iv: iv);
44 1 : final hash = CryptoUtils.sha256(input: data);
45 1 : return EncryptedFile(
46 : data: data,
47 2 : k: base64Url.encode(key).replaceAll('=', ''),
48 2 : iv: base64.encode(iv).replaceAll('=', ''),
49 2 : sha256: base64.encode(hash).replaceAll('=', ''),
50 : );
51 : }
52 :
53 : /// you would likely want to use [NativeImplementations] and
54 : /// [Client.nativeImplementations] instead
55 1 : Future<Uint8List?> decryptFileImplementation(EncryptedFile input) async {
56 4 : if (base64.encode(CryptoUtils.sha256(input: input.data)) !=
57 2 : base64.normalize(input.sha256)) {
58 : return null;
59 : }
60 :
61 3 : final key = base64decodeUnpadded(base64.normalize(input.k));
62 3 : final iv = base64decodeUnpadded(base64.normalize(input.iv));
63 2 : return CryptoUtils.aesCtr(input: input.data, key: key, iv: iv);
64 : }
|