Skip to content

Commit

Permalink
fix: defer AES CBC w/ HMAC decryption after tag verification passes
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Apr 9, 2021
1 parent d0a26bd commit 579485c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 19 deletions.
22 changes: 12 additions & 10 deletions src/runtime/browser/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,6 @@ async function cbcDecrypt(
false,
['sign'],
)
let plaintext!: Uint8Array

try {
plaintext = new Uint8Array(
await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext),
)
} catch {
//
}

const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3))
const expectedTag = new Uint8Array(
Expand All @@ -54,8 +45,19 @@ async function cbcDecrypt(
} catch {
//
}
if (!macCheckPassed) {
throw new JWEDecryptionFailed()
}

if (!plaintext || !macCheckPassed) {
let plaintext!: Uint8Array
try {
plaintext = new Uint8Array(
await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext),
)
} catch {
//
}
if (!plaintext) {
throw new JWEDecryptionFailed()
}

Expand Down
20 changes: 11 additions & 9 deletions src/runtime/node/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,6 @@ async function cbcDecrypt(
throw new JOSENotSupported(`alg ${enc} is unsupported either by your javascript runtime`)
}

let plaintext!: Uint8Array
try {
const cipher = createDecipheriv(algorithm, encKey, iv)
plaintext = concat(cipher.update(ciphertext), cipher.final())
} catch {
//
}

const expectedTag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize)

let macCheckPassed!: boolean
Expand All @@ -51,8 +43,18 @@ async function cbcDecrypt(
} catch {
//
}
if (!macCheckPassed) {
throw new JWEDecryptionFailed()
}

if (!plaintext || !macCheckPassed) {
let plaintext!: Uint8Array
try {
const cipher = createDecipheriv(algorithm, encKey, iv)
plaintext = concat(cipher.update(ciphertext), cipher.final())
} catch {
//
}
if (!plaintext) {
throw new JWEDecryptionFailed()
}

Expand Down

0 comments on commit 579485c

Please sign in to comment.