UNPKG

zk-email-light

Version:
65 lines 2.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sha256Pad = exports.shaCircuitInputs = exports.sha256 = void 0; const crypto_1 = require("crypto"); const dkim_verifier_1 = require("dkim-verifier"); const input_1 = require("./input"); const sha256 = (input) => (0, crypto_1.createHash)("sha256").update(input).digest("hex"); exports.sha256 = sha256; const shaCircuitInputs = (emailRaw) => { const { canonicalizedHeaders } = (0, dkim_verifier_1.parseEmailToCanonicalized)(emailRaw); const bufferMessage = Buffer.from(canonicalizedHeaders, "ascii"); const { paddedInput, paddedInLength } = (0, exports.sha256Pad)(bufferMessage, input_1.SHA_PADDED_MESSAGE_LENGTH); return { paddedIn: Array.from(paddedInput).map(Number), paddedInLength, }; }; exports.shaCircuitInputs = shaCircuitInputs; // Copy from https://github.com/zkemail/zk-email-verify/tree/main/packages/helpers // Works only on 32 bit sha text lengths const int64toBytes = (num) => { const arr = new ArrayBuffer(8); // an Int32 takes 4 bytes const view = new DataView(arr); view.setInt32(4, num, false); // byteOffset = 0; litteEndian = false return new Uint8Array(arr); }; const mergeUInt8Arrays = (a1, a2) => { // sum of individual array lengths const mergedArray = new Uint8Array(a1.length + a2.length); mergedArray.set(a1); mergedArray.set(a2, a1.length); return mergedArray; }; // Works only on 32 bit sha text lengths const int8toBytes = (num) => { const arr = new ArrayBuffer(1); // an Int8 takes 4 bytes const view = new DataView(arr); view.setUint8(0, num); // byteOffset = 0; litteEndian = false return new Uint8Array(arr); }; // Puts an end selector, a bunch of 0s, then the length, then fill the rest with 0s. const sha256Pad = (message, maxShaBytes) => { const msgLen = message.length * 8; // bytes to bits const msgLenBytes = int64toBytes(msgLen); let res = mergeUInt8Arrays(message, int8toBytes(2 ** 7)); // Add the 1 on the end, length 505 // while ((prehash_prepad_m.length * 8 + length_in_bytes.length * 8) % 512 !== 0) { while ((res.length * 8 + msgLenBytes.length * 8) % 512 !== 0) { res = mergeUInt8Arrays(res, int8toBytes(0)); } res = mergeUInt8Arrays(res, msgLenBytes); if ((res.length * 8) % 512 !== 0) throw new Error("Padding did not complete properly!"); const messageLen = res.length; while (res.length < maxShaBytes) { res = mergeUInt8Arrays(res, int64toBytes(0)); } if (res.length !== maxShaBytes) throw new Error(`Padding to max length did not complete properly! Your padded message is ${res.length} long but max is ${maxShaBytes}!`); return { paddedInput: res, paddedInLength: messageLen, }; }; exports.sha256Pad = sha256Pad; //# sourceMappingURL=sha.js.map