@sebastianp265/safe-server-side-storage-client
Version:
Library for Confidential Server-Side Message Storage Using the Labyrinth Protocol
68 lines (67 loc) • 1.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CryptoAssertionError = void 0;
exports.random = random;
exports.cryptoAssert = cryptoAssert;
exports.bytes_equal = bytes_equal;
exports.concat = concat;
exports.asciiStringToBytes = asciiStringToBytes;
exports.bytesToAsciiString = bytesToAsciiString;
const webcrypto_1 = require("@noble/ciphers/webcrypto");
function random(numberOfBytes) {
return (0, webcrypto_1.randomBytes)(numberOfBytes);
}
function cryptoAssert(expression) {
if (!expression)
throw new CryptoAssertionError();
}
class CryptoAssertionError extends Error {
constructor() {
super();
Object.setPrototypeOf(this, CryptoAssertionError);
}
}
exports.CryptoAssertionError = CryptoAssertionError;
function bytes_equal(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function concat(...arrays) {
const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const arr of arrays) {
result.set(arr, offset);
offset += arr.length;
}
return result;
}
// TODO: replace with more efficient approach after writing tests
function asciiStringToBytes(ascii) {
const bytes = new Uint8Array(ascii.length);
for (let i = 0; i < bytes.length; i++) {
const charCode = ascii.charCodeAt(i);
if (charCode > 255) {
throw new Error("Only ascii characters are allowed");
}
bytes[i] = charCode;
}
return bytes;
}
function bytesToAsciiString(bytes) {
let ascii = "";
for (const charCode of bytes) {
if (charCode > 255) {
throw new Error("Only ascii characters are allowed");
}
ascii += String.fromCharCode(charCode);
}
return ascii;
}