aead-stream
Version:
Authenticated encryption on arbitrary large files
90 lines (89 loc) • 3.13 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeUint32 = exports.encodeUint32 = exports.shift = exports.prepend = exports.concat = exports.webcrypto = void 0;
async function webcrypto() {
if (typeof window === "undefined") {
const { webcrypto } = await Promise.resolve().then(() => __importStar(require("crypto")));
return webcrypto;
}
else {
return window.crypto;
}
}
exports.webcrypto = webcrypto;
function concat(...arrays) {
const size = arrays.reduce((acc, cur) => acc + cur.length, 0);
const merged = new Uint8Array(size);
let offset = 0;
for (const array of arrays) {
merged.set(array, offset);
offset += array.length;
}
return merged;
}
exports.concat = concat;
async function* prepend(prefix, stream) {
yield prefix;
yield* stream;
}
exports.prepend = prepend;
async function shift(length, stream) {
const prefix = new Uint8Array(length);
let offset = 0;
const iterator = stream[Symbol.asyncIterator]();
while (true) {
const { done, value } = await iterator.next();
if (done) {
throw new Error("Buffer underflow");
}
else {
const chunk = value;
if (chunk.length < length - offset) {
prefix.set(chunk, offset);
offset += chunk.length;
}
else {
const slice = chunk.slice(0, length - offset);
prefix.set(slice, offset);
return [prefix, prepend(chunk.slice(slice.length), stream)];
}
}
}
}
exports.shift = shift;
function encodeUint32(num) {
const buffer = new ArrayBuffer(4);
new DataView(buffer).setUint32(0, num);
return new Uint8Array(buffer);
}
exports.encodeUint32 = encodeUint32;
function decodeUint32(encoded) {
if (encoded.length != 4) {
throw new Error("invalid input: length != 4");
}
return new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength).getUint32(0);
}
exports.decodeUint32 = decodeUint32;