From 5c98c7ff92d2dab8136e031f9c713d61a0c8fc76 Mon Sep 17 00:00:00 2001 From: larabr <7375870+larabr@users.noreply.github.com> Date: Thu, 11 Apr 2024 13:55:36 +0200 Subject: [PATCH] Add `Argon2S2K.reloadWasmModule()` for manually triggering memory deallocation --- openpgp.d.ts | 1 + src/type/s2k/argon2.js | 12 +++++++++--- test/benchmarks/memory_usage.js | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/openpgp.d.ts b/openpgp.d.ts index b85a652e1..6ec283b06 100644 --- a/openpgp.d.ts +++ b/openpgp.d.ts @@ -925,6 +925,7 @@ export namespace enums { } export declare class Argon2S2K { + static reloadWasmModule(): void; constructor(config: Config); salt: Uint8Array; /** @throws Argon2OutOfMemoryError */ diff --git a/src/type/s2k/argon2.js b/src/type/s2k/argon2.js index f79e3ef6f..4a1a82245 100644 --- a/src/type/s2k/argon2.js +++ b/src/type/s2k/argon2.js @@ -26,6 +26,14 @@ let argon2Promise; const ARGON2_WASM_MEMORY_THRESHOLD_RELOAD = 2 << 19; class Argon2S2K { + static reloadWasmModule() { + if (!loadArgonWasmModule) return; + + // it will be awaited if needed at the next `produceKey` invocation + argon2Promise = loadArgonWasmModule(); + argon2Promise.catch(() => {}); + } + /** * @param {Object} [config] - Full configuration, defaults to openpgp.config */ @@ -114,9 +122,7 @@ class Argon2S2K { // a lot of memory was used, reload to deallocate if (decodedM > ARGON2_WASM_MEMORY_THRESHOLD_RELOAD) { - // it will be awaited if needed at the next `produceKey` invocation - argon2Promise = loadArgonWasmModule(); - argon2Promise.catch(() => {}); + Argon2S2K.reloadWasmModule(); } return hash; } catch (e) { diff --git a/test/benchmarks/memory_usage.js b/test/benchmarks/memory_usage.js index 58166105e..0a2ace390 100644 --- a/test/benchmarks/memory_usage.js +++ b/test/benchmarks/memory_usage.js @@ -336,6 +336,20 @@ class MemoryBenchamrkSuite { }); }); + suite.add('openpgp.encrypt/decryptSessionKeys (argon2)', async () => { + const config = { s2kType: openpgp.enums.s2k.argon2 }; + const passwords = 'password'; + const sessionKey = { + algorithm: 'aes128', + data: require('crypto').getRandomValues(new Uint8Array(16)) + }; + const encrypted = await openpgp.encryptSessionKey({ ...sessionKey, passwords, config, format: 'object' }); + assert(encrypted.packets.length === 1); + const skesk = encrypted.packets[0]; + assert(skesk.s2k.type === 'argon2'); + await openpgp.decryptSessionKeys({ message: encrypted, passwords }); + }); + const stats = await suite.run(); // Print JSON stats to stdout console.log(JSON.stringify(stats, null, 4));