import { describe, it } from '@paulmillr/jsbt/test.js'; import { deepStrictEqual as eql, throws } from 'node:assert'; import { pathToFileURL } from 'node:url'; import { aeskw, aeskwp, cbc, cfb, ctr, ecb, gcm, gcmsiv } from '../src/aes.ts'; import { chacha20poly1305, xchacha20poly1305 } from '../src/chacha.ts'; import { xsalsa20poly1305 } from '../src/salsa.ts'; import { managedNonce, randomBytes, wrapCipher } from '../src/utils.ts'; import { TYPE_TEST, unalign } from './utils.ts'; const BT = { describe, it }; export function test( variant = 'noble', platform = { aeskw, aeskwp, cbc, cfb, ctr, ecb, gcm, gcmsiv, chacha20poly1305, xchacha20poly1305, xsalsa20poly1305, }, { describe, it } = BT ) { const { aeskw, aeskwp, cbc, cfb, ctr, ecb, gcm, gcmsiv, chacha20poly1305, xchacha20poly1305, xsalsa20poly1305, } = platform; const CIPHERS = { xsalsa20poly1305: { fn: xsalsa20poly1305, keyLen: 32, withNonce: true, withOutput: true, }, chacha20poly1305: { fn: chacha20poly1305, keyLen: 32, withNonce: true, withOutput: true, withAAD: true, }, xchacha20poly1305: { fn: xchacha20poly1305, keyLen: 32, withNonce: true, withOutput: true, withAAD: true, }, }; for (const keyLen of [16, 24, 32]) { for (const [name, fn] of Object.entries({ cbc, ctr, cfb })) CIPHERS[`${name}_${keyLen * 8}`] = { fn, keyLen, withNonce: true, withOutput: true }; for (const [name, fn] of Object.entries({ gcm, gcmsiv })) CIPHERS[`${name}_${keyLen * 8}`] = { fn, keyLen, withNonce: true, withAAD: true }; CIPHERS[`ecb_${keyLen * 8}`] = { fn: ecb, keyLen, withNonce: false, withOutput: true }; CIPHERS[`aeskw_${keyLen * 8}`] = { fn: aeskw, keyLen, withNonce: false, blockSize: 8, minLength: 16, }; CIPHERS[`aeskwp_${keyLen * 8}`] = { fn: aeskwp, keyLen, disableEmptyBlock: true }; } for (const k in CIPHERS) { const opts = CIPHERS[k]; if (!opts.withNonce) continue; CIPHERS[`${k}_managedNonce`] = { ...opts, fn: managedNonce(opts.fn), withNonce: false, withOutput: false, }; } CIPHERS.managedCbcNoPadding = { fn: managedNonce(cbc), keyLen: 32, args: [{ disablePadding: true }], blockSize: 16, withOutput: false, }; const checkBlockSize = (opts, len) => { if (opts.minLength && len < opts.minLength) return false; if (!len && opts.disableEmptyBlock) return false; if (!opts.blockSize) return true; if (len % opts.blockSize === 0) return true; return false; }; const createCipher = (opts, key, nonce, AAD) => { const { fn, withNonce } = opts; const args = [key]; if (withNonce) args.push(nonce); if (AAD !== undefined && opts.withAAD) args.push(AAD); return fn(...args, ...(opts.args || [])); }; const initCipher = (opts) => { const { fn, keyLen, withNonce } = opts; const key = randomBytes(keyLen); const nonce = withNonce ? randomBytes(fn.nonceLength) : undefined; const c = createCipher(opts, key, nonce); return { c, key, nonce, copy: { key: key.slice(), nonce: nonce?.slice() } }; }; describe(`Basic (${variant})`, () => { for (const k in CIPHERS) { { const opts = CIPHERS[k]; it(`${k}: blockSize`, () => { const { c, key, nonce, copy } = initCipher(opts); const msg = new Uint8Array(opts.blockSize).fill(12); const msgCopy = msg.slice(); if (checkBlockSize(opts, msgCopy.length)) { eql(c.decrypt(c.encrypt(msgCopy)), msg); eql(msg, msgCopy); // Verify that key/nonce is not modified eql(key, copy.key); eql(nonce, copy.nonce); } }); if (opts.blockSize) { it(`${k}: wrong blockSize`, () => { const { c } = initCipher(opts); const msg = new Uint8Array(opts.blockSize - 1).fill(12); throws(() => c.encrypt(msg)); throws(() => c.decrypt(msg)); }); } it(`${k}: round-trip`, () => { // slice, so cipher has no way to corrupt msg const msg = new Uint8Array(2).fill(12); const msgCopy = msg.slice(); if (checkBlockSize(opts, msgCopy.length)) { const { c, key, nonce, copy } = initCipher(opts); eql(c.decrypt(c.encrypt(msgCopy)), msg); eql(msg, msgCopy); } const msg2 = new Uint8Array(2048).fill(255); const msg2Copy = msg2.slice(); if (checkBlockSize(opts, msg2Copy.length)) { const { c, key, nonce, copy } = initCipher(opts); eql(c.decrypt(c.encrypt(msg2)), msg2); eql(msg2, msg2Copy); } const { c, key, nonce, copy } = initCipher(opts); const msg3 = new Uint8Array(256).fill(3); const msg3Copy = msg3.slice(); if (!checkBlockSize(opts, msg3Copy.length)) { eql(c.decrypt(c.encrypt(msg3Copy)), msg3); eql(msg3, msg3Copy); } // Verify that key/nonce is not modified eql(key, copy.key); eql(nonce, copy.nonce); }); it(`${k}: different sizes`, () => { for (let i = 0; i < 2048; i++) { const msg = new Uint8Array(i).fill(i); const msgCopy = msg.slice(); if (checkBlockSize(opts, msgCopy.length)) { const { c, key, nonce, copy } = initCipher(opts); eql(c.decrypt(c.encrypt(msg)), msg); eql(msg, msgCopy); eql(key, copy.key); eql(nonce, copy.nonce); } } }); it(`${k}: unalign 0..7`, () => { for (let i = 0; i < 8; i++) { const { fn, keyLen, withNonce } = opts; const key = unalign(randomBytes(keyLen), i); const nonce = withNonce ? unalign(randomBytes(fn.nonceLength), i) : undefined; const AAD = unalign(randomBytes(64), i); const msg = unalign(new Uint8Array(2048).fill(255), i); if (checkBlockSize(opts, msg.length)) { const cipher = createCipher(opts, key, nonce, AAD); const encrypted = unalign(cipher.encrypt(msg), i); const decrypted = cipher.decrypt(encrypted); eql(decrypted, msg, `${k}: unalign ${i}`); } } }); const overlapTest = (a, b, cb) => { const buffer = new Uint8Array(a.length + b.length); let inputPos = 0; let outputPos = a.length; const t = () => { const aBuf = buffer.subarray(inputPos, inputPos + a.length); const bBuf = buffer.subarray(outputPos, outputPos + b.length); cb(aBuf, bBuf, buffer); }; for (; outputPos > 0; outputPos--) t(); // first we decreate outputPos for (; inputPos <= b.length; inputPos++) t(); // then we move inputPos }; const getIntersection = (a, b) => { if (a.buffer !== b.buffer) return new Uint8Array(0); const overlapStart = Math.max(a.byteOffset, b.byteOffset); const overlapEnd = Math.min(a.byteOffset + a.byteLength, b.byteOffset + b.byteLength); if (overlapStart >= overlapEnd) return new Uint8Array(0); return new Uint8Array(a.buffer, overlapStart, overlapEnd - overlapStart); }; // it('overlapTest test', () => { // // Test: // overlapTest(new Uint8Array(5), new Uint8Array(4), (a, b, all) => { // all.fill(0); // a.fill(1); // b.fill(2); // getIntersection(a, b).fill(3); // console.log('AB', a, b, all); // }); // throw 'lol'; // }); it(`${k} (re-use)`, () => { const { fn, keyLen, withNonce, withOutput } = opts; const key = randomBytes(keyLen); const nonce = withNonce ? randomBytes(fn.nonceLength) : undefined; const AAD = randomBytes(64); const supportedLength = Math.max(2 * fn.blockSize, opts.minLength || 0); const sample = randomBytes(supportedLength); let cipher = createCipher(opts, key, nonce, AAD); if (!withOutput) { if (k.includes('managed')) { // managedNonce deliberately has no destination-buffer API because it prepends a // generated nonce. Still exercise the entry instead of silently skipping by arity. const sampleCopy = sample.slice(); const encrypted = cipher.encrypt(sample); eql(sample, sampleCopy); eql(createCipher(opts, key, nonce, AAD).decrypt(encrypted), sample); } else { // Wrapped ciphers without output support reject an explicitly supplied buffer. throws(() => cipher.encrypt(sample, new Uint8Array(sample.length))); cipher = createCipher(opts, key, nonce, AAD); const encrypted = cipher.encrypt(sample); throws(() => cipher.decrypt(encrypted, new Uint8Array(encrypted.length))); } return; } const pcksOutput = (len) => { const remaining = len % fn.blockSize; let left = fn.blockSize - remaining; if (!left) left = fn.blockSize; // if no bytes left, create empty padding block return left; }; const messageLengths = [ 4, 8, fn.blockSize, 2 * fn.blockSize, 5 * fn.blockSize, 10 * fn.blockSize, ]; messageLengths.push((1.5 * fn.blockSize) | 0); messageLengths.push((1.75 * fn.blockSize) | 0); const stats = { e_ok: 0, e_fail: 0, d_ok: 0, d_fail: 0 }; const isAesOutput = ['cbc', 'ctr', 'cfb', 'ecb'].some((name) => k.includes(name)); const rejectsOverlap = (input, output) => { const overlaps = getIntersection(input, output).length !== 0; if (k.includes('cfb')) return overlaps; return ( ['cbc', 'ctr', 'ecb'].some((name) => k.includes(name)) && overlaps && input.byteOffset < output.byteOffset ); }; const mustReject = (input, output) => (isAesOutput && output.byteOffset % 4 !== 0) || rejectsOverlap(input, output); for (const msgLen of messageLengths) { const msg = randomBytes(msgLen); const key = randomBytes(keyLen); const nonce = withNonce ? randomBytes(fn.nonceLength) : undefined; const AAD = randomBytes(64); let cipher = createCipher(opts, key, nonce, AAD); const pkcs5 = ['cbc', 'ecb'].some((name) => k.includes(name)); for (let fillByte = 0; fillByte < 256; fillByte++) { // Tmp buffer let outLen = msg.length; if (fn.tagLength) outLen += fn.tagLength; if (k === 'xsalsa20poly1305') outLen += 16; if (pkcs5) outLen += pcksOutput(msg.length); // Expected result cipher = createCipher(opts, key, nonce, AAD); const exp = cipher.encrypt(msg); const out = new Uint8Array(outLen); // First pass cipher = createCipher(opts, key, nonce, AAD); const res = cipher.encrypt(msg, out); eql(res, exp); // check if res is output eql(res, out.subarray(res.byteOffset, res.byteOffset + res.length)); eql(res.buffer, out.buffer); // make sure that underlying array buffer is same // Second pass out.fill(fillByte); cipher = createCipher(opts, key, nonce, AAD); const res2 = cipher.encrypt(msg, out); eql(res2, exp); eql(res2, out.subarray(res2.byteOffset, res2.byteOffset + res2.length)); eql(res2.buffer, out.buffer); // make sure that underlying array buffer is same // Exact in-place overlap is supported except by CFB. cipher = createCipher(opts, key, nonce, AAD); out.fill(fillByte); out.set(msg); const msg2 = out.subarray(0, msg.length); if (mustReject(msg2, out)) throws(() => cipher.encrypt(msg2, out)); else eql(cipher.encrypt(msg2, out), exp); overlapTest(msg2, out, (msg2, out2, all) => { all.fill(fillByte); msg2.set(msg); cipher = createCipher(opts, key, nonce, AAD); if (mustReject(msg2, out2)) { throws(() => cipher.encrypt(msg2, out2)); stats.e_fail++; return; } const newOut = cipher.encrypt(msg2, out2); stats.e_ok++; eql(newOut.buffer, all.buffer); // make sure that underlying array buffer is same eql(newOut.buffer, out2.buffer); // make sure that underlying array buffer is same eql(newOut, exp); }); // Expected result cipher = createCipher(opts, key, nonce, AAD); const input = cipher.encrypt(msg); // Tmp buffer outLen = msg.length; if (k === 'xsalsa20poly1305') outLen += 32 + 16; if (pkcs5) outLen += pcksOutput(msg.length); const decOut = new Uint8Array(outLen); // First pass const dec = cipher.decrypt(input, decOut); eql(dec, msg); eql(dec, decOut.subarray(dec.byteOffset, dec.byteOffset + dec.length)); eql(dec.buffer, decOut.buffer); // make sure that underlying array buffer is same // Second pass decOut.fill(fillByte); const dec2 = cipher.decrypt(input, decOut); eql(dec2, msg); eql(dec2, decOut.subarray(dec2.byteOffset, dec2.byteOffset + dec2.length)); eql(dec2.buffer, decOut.buffer); // make sure that underlying array buffer is same // Exact in-place overlap is supported except by CFB. const tmp = new Uint8Array(Math.max(decOut.length, input.length)); tmp.fill(fillByte); tmp.set(input); const out2 = tmp.subarray(0, decOut.length); const input2 = tmp.subarray(0, input.length); if (mustReject(input2, out2)) throws(() => cipher.decrypt(input2, out2)); else eql(cipher.decrypt(input2, out2), msg); overlapTest(input2, out2, (input2, out2, all) => { all.fill(fillByte); input2.set(input); if (mustReject(input2, out2)) { throws(() => cipher.decrypt(input2, out2)); stats.d_fail++; return; } const newOut = cipher.decrypt(input2, out2); stats.d_ok++; eql(newOut.buffer, all.buffer); // make sure that underlying array buffer is same eql(newOut.buffer, out2.buffer); // make sure that underlying array buffer is same eql(newOut, msg); }); } } eql(stats.e_ok > 0, true, `${k}: expected accepted encrypt overlaps`); eql(stats.d_ok > 0, true, `${k}: expected accepted decrypt overlaps`); if (isAesOutput) { eql(stats.e_fail > 0, true, `${k}: expected rejected encrypt overlaps`); eql(stats.d_fail > 0, true, `${k}: expected rejected decrypt overlaps`); } else { eql(stats.e_fail, 0, `${k}: encrypt overlap failures`); eql(stats.d_fail, 0, `${k}: decrypt overlap failures`); } }); const isRawArxAead = ['xsalsa20poly1305', 'xchacha20poly1305', 'chacha20poly1305'].includes(k) && !k.includes('managedNonce'); if (isRawArxAead) it('unaligned', () => { const isSalsa = k.includes('salsa'); const { fn, keyLen } = opts; const msg = new TextEncoder().encode('hello'); const key = randomBytes(keyLen); const nonce = randomBytes(fn.nonceLength); const sample_enc = fn(key.slice(), nonce.slice()).encrypt(msg); const L = msg.length; const ciphertextLen = sample_enc.length; const tmp = new Uint8Array(512).fill(5); for (let start = 0; start < 32; start++) { const i = {}; i.p_start = start; i.p_end = start + L; // .encrypt() output needs L + 32 if (isSalsa) { i.c_start = i.p_end; i.c_end = i.c_start + L + 32; i.dec_start = i.c_end; i.dec_end = i.dec_start + L + 48; } else { i.c_start = i.p_end; i.c_end = i.c_start + ciphertextLen; i.dec_start = i.c_end; i.dec_end = i.dec_start + L; } tmp.set(msg, i.p_start); const cipher = fn(key, nonce); const buf_p = tmp.subarray(i.p_start, i.p_end); const buf_dec = tmp.subarray(i.dec_start, i.dec_end); // Encrypt let ciphertext = cipher.encrypt(buf_p, tmp.subarray(i.c_start, i.c_end)); eql(ciphertext, sample_enc, '.encrypt() differs'); // Decrypt let plaintext = cipher.decrypt(ciphertext, buf_dec); eql(msg, plaintext, '.decrypt() differs'); } // deepStrictEqual(data.subarray(0, 8), data.subarray(32, 40)) }); if (isRawArxAead) it('be able to reuse input and output arrays', () => { const isSalsa = k === 'xsalsa20poly1305'; const { fn, keyLen } = opts; const TMP_FILL_BYTE = 0; const msg = new TextEncoder().encode('hello'); const key = new Uint8Array(keyLen).fill(1); const nonce = new Uint8Array(fn.nonceLength).fill(2); let tmp; const get = () => fn(key, nonce); const initTmp = () => (tmp = new Uint8Array(64).fill(TMP_FILL_BYTE)); const encryptedMsg = get().encrypt(msg); const decryptedMsg = fn(key, nonce).decrypt(encryptedMsg); // == msg eql(decryptedMsg, msg, 'decryption works'); const L = msg.length; // To encrypt 5-byte input, salsa needs 5 + 32 byte (half-block) output. // However, it would effectively ONLY use 5 + 16 bytes (nonce size). // And the output would be 5 + 16. // To encrypt 5-byte input, chacha needs 5 + 16 byte (nonce size) output // Part 1: Simply use existing `tmp` initTmp(); eql( get().encrypt(msg, tmp.subarray(0, isSalsa ? L + 32 : L + 16)), encryptedMsg, 'example 1' ); // To decrypt eql( get().decrypt(encryptedMsg, tmp.subarray(0, isSalsa ? L + 48 : 5)), msg, 'example 2' ); // Part 2: Share `tmp` between input and output initTmp(); tmp.set(msg, 0); const reusedEnc = get().encrypt(msg, tmp.subarray(0, isSalsa ? L + 32 : L + 16)); eql(reusedEnc, encryptedMsg, 'example 3'); const reusedDec = get().decrypt(reusedEnc, tmp.subarray(0, isSalsa ? L + 48 : 5)); eql(reusedDec, msg, 'example 4'); }); if (!k.includes('managed')) { it(`${k}: prohibit encrypting twice`, () => { const { c } = initCipher(opts); let length = Math.max(10, opts.minLength || 0); if (opts.blockSize) length = Math.ceil(length / opts.blockSize) * opts.blockSize; const msg = new Uint8Array(length); c.encrypt(msg); throws(() => { c.encrypt(msg); }); }); } } } }); describe(`input validation (${variant})`, () => { const INVALID_BYTE_ARRAYS = TYPE_TEST.bytes; it('advertise AAD support explicitly', () => { const meta = { xsalsa20poly1305: (xsalsa20poly1305 as any).withAAD, chacha20poly1305: (chacha20poly1305 as any).withAAD, xchacha20poly1305: (xchacha20poly1305 as any).withAAD, cbc: (cbc as any).withAAD, gcm: (gcm as any).withAAD, gcmsiv: (gcmsiv as any).withAAD, }; eql(meta, { xsalsa20poly1305: undefined, chacha20poly1305: true, xchacha20poly1305: true, cbc: undefined, gcm: true, gcmsiv: true, }); }); it('wrapCipher accepts explicit AAD support with rest args', () => { const seen = []; const cipher = wrapCipher( { blockSize: 1, nonceLength: 1, tagLength: 1, withAAD: true }, (key, nonce, ...AAD) => { seen.push(AAD); return { encrypt: (data) => data, decrypt: (data) => data, }; } ); const aad = new Uint8Array([3]); cipher(new Uint8Array(1), new Uint8Array(1), aad); eql(seen, [[aad]]); eql(cipher.withAAD, true); }); it('reject AAD after no-AAD options', () => { const key = new Uint8Array(16); const nonce = new Uint8Array(16); const aad = new Uint8Array(16); throws(() => (cbc as any)(key, nonce, { disablePadding: true }, aad)); throws(() => (ecb as any)(key, { disablePadding: true }, aad)); }); it('CBC and ECB enforce block sizes when padding is disabled', () => { const key = new Uint8Array(16); const iv = new Uint8Array(16); const create = [ () => cbc(key, iv, { disablePadding: true }), () => ecb(key, { disablePadding: true }), ]; for (const init of create) { for (const length of [15, 17]) { throws(() => init().encrypt(new Uint8Array(length))); throws(() => init().decrypt(new Uint8Array(length))); } const block = new Uint8Array(16); const cipher = init(); eql(cipher.decrypt(cipher.encrypt(block)), block); } }); for (const k in CIPHERS) { if (k.includes('managed')) continue; { const opts = CIPHERS[k]; const { fn, keyLen } = opts; describe(k, () => { // Constructor tests it('reject invalid key', () => { const nonce = new Uint8Array(fn.nonceLength); const aad = new Uint8Array(16); for (const invalid of INVALID_BYTE_ARRAYS) { throws(() => fn(invalid, nonce), 'non-u8a'); } // Test wrong key length const msg = new Uint8Array(1); throws(() => fn(new Uint8Array(keyLen + 1), nonce).encrypt(msg), 'key length + 1'); throws(() => fn(new Uint8Array(keyLen - 1), nonce).encrypt(msg), 'key length - 1'); }); if (fn.nonceLength) { it('reject invalid nonce', () => { const key = new Uint8Array(keyLen); const aad = new Uint8Array(16); for (const invalid of INVALID_BYTE_ARRAYS) { throws(() => fn(key, invalid)); } // Test wrong nonce length if (fn.varSizeNonce) return; const msg = new Uint8Array(1); throws(() => fn(key, new Uint8Array(fn.nonceLength + 1)).encrypt(msg)); throws(() => fn(key, new Uint8Array(fn.nonceLength - 1)).encrypt(msg)); }); } if (fn.tagLength && k !== 'xsalsa20poly1305') { it('reject invalid AAD', () => { const key = new Uint8Array(keyLen); const nonce = new Uint8Array(fn.nonceLength); for (const invalid of INVALID_BYTE_ARRAYS) { if (invalid == null) return; throws(() => fn(key, nonce, invalid)); } }); } if (!opts.withAAD) { it('reject AAD', () => { const key = new Uint8Array(keyLen); const nonce = fn.nonceLength ? new Uint8Array(fn.nonceLength) : undefined; const aad = new Uint8Array(16); if (fn.nonceLength) throws(() => fn(key, nonce, aad)); else throws(() => fn(key, aad)); }); } // Method tests it('reject invalid encrypt input', () => { const key = new Uint8Array(keyLen); const nonce = fn.nonceLength ? new Uint8Array(fn.nonceLength) : undefined; const cipher = nonce ? fn(key, nonce) : fn(key); for (const invalid of INVALID_BYTE_ARRAYS) { throws(() => cipher.encrypt(invalid)); } }); it('reject invalid decrypt input', () => { const key = new Uint8Array(keyLen); const nonce = fn.nonceLength ? new Uint8Array(fn.nonceLength) : undefined; const cipher = nonce ? fn(key, nonce) : fn(key); for (const invalid of INVALID_BYTE_ARRAYS) { throws(() => cipher.decrypt(invalid)); } }); if (opts.blockSize) { it('validate block size on encrypt', () => { const key = new Uint8Array(keyLen); const nonce = fn.nonceLength ? new Uint8Array(fn.nonceLength) : undefined; const cipher = nonce ? fn(key, nonce) : fn(key); // Test invalid block size if padding is disabled if (opts.disablePadding) { throws(() => cipher.encrypt(new Uint8Array(opts.blockSize - 1))); throws(() => cipher.encrypt(new Uint8Array(opts.blockSize + 1))); } }); } if (fn.tagLength) { it('validate tag length on decrypt', () => { const key = new Uint8Array(keyLen); const nonce = new Uint8Array(fn.nonceLength); const cipher = fn(key, nonce); // Test ciphertext lengths that would result in invalid tag throws(() => cipher.decrypt(new Uint8Array(fn.tagLength - 1))); throws(() => cipher.decrypt(new Uint8Array(15))); }); } }); } } }); } if (import.meta.url === pathToFileURL(process.argv[1]).href) test(); it.runWhen(import.meta.url);