Skip to content

Commit

Permalink
webcrypto: improve managedNonce
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmillr committed Nov 26, 2024
1 parent 4f8ca6a commit 77f1562
Showing 1 changed file with 2 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/webcrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,17 @@ type CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) =>

// Uses CSPRG for nonce, nonce injected in ciphertext
export function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T> {
anumber(fn.nonceLength);
const { nonceLength } = fn;
anumber(nonceLength);
return ((key: Uint8Array, ...args: any[]): any => ({
encrypt(plaintext: Uint8Array, ...argsEnc: any[]) {
const { nonceLength } = fn;
const nonce = randomBytes(nonceLength);
const ciphertext = (fn(key, nonce, ...args).encrypt as any)(plaintext, ...argsEnc);
const out = concatBytes(nonce, ciphertext);
ciphertext.fill(0);
return out;
},
decrypt(ciphertext: Uint8Array, ...argsDec: any[]) {
const { nonceLength } = fn;
const nonce = ciphertext.subarray(0, nonceLength);
const data = ciphertext.subarray(nonceLength);
return (fn(key, nonce, ...args).decrypt as any)(data, ...argsDec);
Expand Down

0 comments on commit 77f1562

Please sign in to comment.