Skip to content

Commit b37576a

Browse files
committed
feat: add frame cryptor.
1 parent 1269dec commit b37576a

File tree

7 files changed

+1633
-0
lines changed

7 files changed

+1633
-0
lines changed

lib/src/e2ee.worker/crypto.dart

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import 'dart:async';
2+
import 'dart:typed_data';
3+
import 'dart:js_util' as jsutil;
4+
import 'dart:html' as html;
5+
6+
import 'package:js/js.dart';
7+
8+
@JS('Promise')
9+
class Promise<T> {
10+
external factory Promise._();
11+
}
12+
13+
@JS('Algorithm')
14+
class Algorithm {
15+
external String get name;
16+
}
17+
18+
@JS('crypto.subtle.encrypt')
19+
external Promise<ByteBuffer> encrypt(
20+
dynamic algorithm,
21+
html.CryptoKey key,
22+
ByteBuffer data,
23+
);
24+
25+
@JS('crypto.subtle.decrypt')
26+
external Promise<ByteBuffer> decrypt(
27+
dynamic algorithm,
28+
html.CryptoKey key,
29+
ByteBuffer data,
30+
);
31+
32+
@JS()
33+
@anonymous
34+
class AesGcmParams {
35+
external factory AesGcmParams({
36+
required String name,
37+
required ByteBuffer iv,
38+
ByteBuffer? additionalData,
39+
int tagLength = 128,
40+
});
41+
}
42+
43+
ByteBuffer jsArrayBufferFrom(List<int> data) {
44+
// Avoid copying if possible
45+
if (data is Uint8List &&
46+
data.offsetInBytes == 0 &&
47+
data.lengthInBytes == data.buffer.lengthInBytes) {
48+
return data.buffer;
49+
}
50+
// Copy
51+
return Uint8List.fromList(data).buffer;
52+
}
53+
54+
@JS('crypto.subtle.importKey')
55+
external Promise<html.CryptoKey> importKey(
56+
String format,
57+
ByteBuffer keyData,
58+
dynamic algorithm,
59+
bool extractable,
60+
List<String> keyUsages,
61+
);
62+
63+
@JS('crypto.subtle.exportKey')
64+
external Promise<ByteBuffer> exportKey(
65+
String format,
66+
html.CryptoKey key,
67+
);
68+
69+
@JS('crypto.subtle.deriveKey')
70+
external Promise<html.CryptoKey> deriveKey(
71+
dynamic algorithm,
72+
html.CryptoKey baseKey,
73+
dynamic derivedKeyAlgorithm,
74+
bool extractable,
75+
List<String> keyUsages);
76+
77+
@JS('crypto.subtle.deriveBits')
78+
external Promise<ByteBuffer> deriveBits(
79+
dynamic algorithm,
80+
html.CryptoKey baseKey,
81+
int length,
82+
);
83+
84+
Future<html.CryptoKey> impportKeyFromRawData(List<int> secretKeyData,
85+
{required String webCryptoAlgorithm,
86+
required List<String> keyUsages}) async {
87+
return jsutil.promiseToFuture<html.CryptoKey>(importKey(
88+
'raw',
89+
jsArrayBufferFrom(secretKeyData),
90+
jsutil.jsify({'name': webCryptoAlgorithm}),
91+
false,
92+
keyUsages,
93+
));
94+
}

0 commit comments

Comments
 (0)