Skip to content

Commit 64a2102

Browse files
refactor: move pbkdf2 derive bits off the main-thread (#233)
1 parent 5a83449 commit 64a2102

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

lib/src/impl_ffi/impl_ffi.pbkdf2.dart

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ final class _Pbkdf2SecretKeyImpl implements Pbkdf2SecretKeyImpl {
7171

7272
return _Scope.async((scope) async {
7373
final out = scope<ffi.Uint8>(lengthInBytes);
74-
_checkOpIsOne(ssl.PKCS5_PBKDF2_HMAC(
74+
_checkOpIsOne(await _PKCS5_PBKDF2_HMAC(
7575
scope.dataAsPointer(_key),
7676
_key.length,
7777
scope.dataAsPointer(salt),
@@ -85,3 +85,35 @@ final class _Pbkdf2SecretKeyImpl implements Pbkdf2SecretKeyImpl {
8585
});
8686
}
8787
}
88+
89+
/// Helper function to run `ssl.PKCS5_PBKDF2_HMAC` in an [Isolate]
90+
/// using [Isolate.run].
91+
///
92+
/// This offloads the computationally expensive PBKDF2 operation to a
93+
/// separate isolate to avoid blocking the main isolate.
94+
///
95+
/// Using this auxiliary function to wrap the call should reduce the risk that
96+
/// unnecessary variables are copied into the closure passed to [Isolate.run].
97+
Future<int> _PKCS5_PBKDF2_HMAC(
98+
ffi.Pointer<ffi.Char> key,
99+
int keyLength,
100+
ffi.Pointer<ffi.Uint8> salt,
101+
int saltLength,
102+
int iterations,
103+
ffi.Pointer<EVP_MD> md,
104+
int lengthInBytes,
105+
ffi.Pointer<ffi.Uint8> out,
106+
) async =>
107+
await Isolate.run(
108+
() => ssl.PKCS5_PBKDF2_HMAC(
109+
key,
110+
keyLength,
111+
salt,
112+
saltLength,
113+
iterations,
114+
md,
115+
lengthInBytes,
116+
out,
117+
),
118+
debugName: 'PKCS5_PBKDF2_HMAC',
119+
);

0 commit comments

Comments
 (0)