Skip to content

Commit

Permalink
crypto: fix passing TypedArray to webcrypto AES methods
Browse files Browse the repository at this point in the history
Refs: https://www.w3.org/TR/WebCryptoAPI/#subtlecrypto-interface
Fixes: #36083

PR-URL: #36087
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
Reviewed-By: Tobias Nießen <[email protected]>
  • Loading branch information
aduh95 authored and nodejs-github-bot committed Nov 13, 2020
1 parent e174afe commit 28f31bd
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
8 changes: 6 additions & 2 deletions lib/internal/crypto/aes.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
'use strict';

const {
ArrayBufferIsView,
ArrayBufferPrototypeSlice,
ArrayFrom,
ArrayPrototypeIncludes,
ArrayPrototypePush,
MathFloor,
Promise,
SafeSet,
TypedArrayPrototypeSlice,
} = primordials;

const {
Expand Down Expand Up @@ -183,8 +185,10 @@ function asyncAesGcmCipher(
let tag;
switch (mode) {
case kWebCryptoCipherDecrypt:
tag = ArrayBufferPrototypeSlice(data, -tagByteLength);
data = ArrayBufferPrototypeSlice(data, 0, -tagByteLength);
const slice = ArrayBufferIsView(data) ?
TypedArrayPrototypeSlice : ArrayBufferPrototypeSlice;
tag = slice(data, -tagByteLength);
data = slice(data, 0, -tagByteLength);
break;
case kWebCryptoCipherEncrypt:
tag = tagByteLength;
Expand Down
40 changes: 39 additions & 1 deletion test/parallel/test-webcrypto-encrypt-decrypt-aes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ if (!common.hasCrypto)
common.skip('missing crypto');

const assert = require('assert');
const { subtle } = require('crypto').webcrypto;
const { getRandomValues, subtle } = require('crypto').webcrypto;

async function testEncrypt({ keyBuffer, algorithm, plaintext, result }) {
const key = await subtle.importKey(
Expand Down Expand Up @@ -196,3 +196,41 @@ async function testDecrypt({ keyBuffer, algorithm, result }) {
await Promise.all(variations);
})().then(common.mustCall());
}

{
(async function() {
const secretKey = await subtle.generateKey(
{
name: 'AES-GCM',
length: 256,
},
false,
['encrypt', 'decrypt'],
);

const iv = getRandomValues(new Uint8Array(12));
const aad = getRandomValues(new Uint8Array(32));

const encrypted = await subtle.encrypt(
{
name: 'AES-GCM',
iv,
additionalData: aad,
tagLength: 128
},
secretKey,
getRandomValues(new Uint8Array(32))
);

await subtle.decrypt(
{
name: 'AES-GCM',
iv,
additionalData: aad,
tagLength: 128,
},
secretKey,
new Uint8Array(encrypted),
);
})().then(common.mustCall());
}

0 comments on commit 28f31bd

Please sign in to comment.