Skip to content

Commit 07c1cd5

Browse files
committed
feat: E2EE for data channel.
1 parent a7fb8e4 commit 07c1cd5

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

lib/src/e2ee/data_channel.dart

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import 'dart:typed_data';
2+
3+
import 'package:cryptography/cryptography.dart';
4+
5+
import 'key_provider.dart';
6+
7+
class DataChannelFrameCryptor {
8+
final KeyProvider keyProvider;
9+
final algorithm = AesGcm.with128bits();
10+
late SecretKey secretKey;
11+
late List<int> nonce;
12+
13+
DataChannelFrameCryptor(
14+
this.keyProvider,
15+
);
16+
17+
Future<void> init() async {
18+
// Generate a secret key
19+
secretKey = await algorithm
20+
.newSecretKeyFromBytes(await keyProvider.exportSharedKey());
21+
print('Secret key: $secretKey');
22+
23+
// Generate a nonce
24+
nonce = algorithm.newNonce();
25+
print('Nonce: $nonce');
26+
}
27+
28+
/// Encrypt
29+
Future<Uint8List> encrypt(Uint8List frame) async {
30+
final secretBox = await algorithm.encrypt(
31+
frame,
32+
secretKey: secretKey,
33+
nonce: nonce,
34+
);
35+
36+
///print('Nonce: ${secretBox.nonce}');
37+
///print('Ciphertext: ${secretBox.cipherText}');
38+
///print('MAC: ${secretBox.mac.bytes}');
39+
return Uint8List.fromList(secretBox.cipherText);
40+
}
41+
42+
/// Decrypt
43+
Future<Uint8List?> decrypt(Uint8List secretBox) async {
44+
final clearText = await algorithm.encrypt(
45+
secretBox,
46+
secretKey: secretKey,
47+
);
48+
//print('Cleartext: $clearText');
49+
return Uint8List.fromList(clearText.cipherText);
50+
}
51+
}

pubspec.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ dependencies:
4444
dart_webrtc: ^1.4.9
4545
sdp_transform: ^0.3.2
4646
web: ^1.0.0
47+
cryptography: ^2.7.0
4748

4849
dev_dependencies:
4950
flutter_test:

0 commit comments

Comments
 (0)