PeculiarVentures / webcrypto-liner

webcrypto-liner is a polyfill that let's down-level User Agents (like IE/Edge) use libraries that depend on WebCrypto. (Keywords: Javascript, WebCrypto, Shim, Polyfill)
MIT License
148 stars 26 forks source link

fix: 'data integrity check failed' when using additionalData #93

Closed jclab-joseph closed 1 year ago

jclab-joseph commented 1 year ago

Using additionalData throws an error. Because asmCrypto looks for additionalData.length, but ArrayBuffer doesn't have length property.

import * as nodeCrypto from 'crypto';
import * as liner from '../src';

const key = Buffer.from('0123456789abcdef0123456789abcdef');
const iv = Buffer.from('000000000000');
const additionalData = Buffer.from('abcd');
const plainText = Buffer.from('abcd');

const cipher = nodeCrypto.createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(additionalData);
const cipherTextBuffers = [];
cipherTextBuffers.push(cipher.update(plainText));
cipherTextBuffers.push(cipher.final());
cipherTextBuffers.push(cipher.getAuthTag());
const cipherText = Buffer.concat(cipherTextBuffers);

const linerCrypto = new liner.Crypto();

(async () => {
  const cryptoKey = await linerCrypto.subtle.importKey('raw', key, 'AES-GCM', true, ['encrypt', 'decrypt']);
  const algorithm = {
    name: "AES-GCM",
    iv: iv,
    additionalData: additionalData,
  } as AesGcmParams;
  const enc = await linerCrypto.subtle.decrypt(algorithm, cryptoKey, cipherText);
  console.log(enc);
})();