UNPKG

@cronstamp/clientlib

Version:

Client library for cronstamp, a blockchain-based document timestamping and verification service.

73 lines 2.37 kB
/* https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest */ import { ErrorTypes, ProcessError } from '../lifecycle/manager.js'; import { toBase64String } from './base-convert.js'; export const defaultAlgo = 'SHA-256'; export const VersionToHashAlgorithm = { 1: 'SHA-256' }; /** * Hash text string and return base64 hash * @param message * @param algo */ export async function hashString(message, algo = defaultAlgo) { const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array return await hashData(msgUint8, algo); } /** * Hash a file and return the base64 encoded hash * @param file * @param algo */ export async function hashFile(file, algo = defaultAlgo) { let buffer = await file.arrayBuffer(); // get byte array of file return await hashData(buffer, algo); } /** * Hash array buffer and return base64 encoded string of the hash * @param buffer * @param algo */ async function hashData(buffer, algo = defaultAlgo) { const hashBuffer = await crypto.subtle.digest(algo, buffer); // hash the message const hashArray = new Uint8Array(hashBuffer); // convert ArrayBuffer to Array return toBase64String(hashArray); // to hex } /** * Check the length of a base64 encoded hash * @param hash * @param algo */ export function isValidHash(hash, algo = defaultAlgo) { let decoded = atob(hash); if ((algo == 'SHA-256' && decoded.length == 256 / 8) || (algo == 'SHA-384' && decoded.length == 384 / 8) || (algo == 'SHA-512' && decoded.length == 512 / 8)) { return true; } else { throw new ProcessError('Invalid hash length for hash "' + hash + '": ' + decoded.length + ' for algorithm ' + algo, ErrorTypes.DOCUMENT_ALTERED); } } /** * Hash two hashes on the same level in the merkle tree, to result in the parent hash * @param hashA * @param hashB */ export async function hashSiblingHashes(hashA, hashB) { // if the other side is empty just one is hashed if (hashA == '' && hashB != '') { return hashString(hashB); } if (hashB == '' && hashA != '') { return hashString(hashA); } // order depends on lexicographical order of hashes if (hashA < hashB) { return hashString(hashA + hashB); } else { return hashString(hashB + hashA); } } //# sourceMappingURL=hash.js.map