UNPKG

@credo-ts/core

Version:

<p align="center"> <br /> <img alt="Credo Logo" src="https://github.com/openwallet-foundation/credo-ts/blob/c7886cb8377ceb8ee4efe8d264211e561a75072d/images/credo-logo.png" height="250px" /> </p> <h1 align="center"><b>Credo - Core</b></h1

75 lines (74 loc) • 2.06 kB
import { TypedArrayEncoder } from "./TypedArrayEncoder.mjs"; import { Hasher } from "../crypto/hashes/Hasher.mjs"; import { VarintEncoder } from "./VarintEncoder.mjs"; //#region src/utils/MultiHashEncoder.ts const multiHashNameMap = { "sha-1": 17, "sha-256": 18, "sha-512": 19, "sha-384": 32 }; const multiHashCodeMap = Object.entries(multiHashNameMap).reduce((map, [hashName, hashCode]) => ({ ...map, [hashCode]: hashName }), {}); var MultiHashEncoder = class MultiHashEncoder { /** * * Encodes a buffer into a hash * * @param buffer the buffer that has to be encoded * @param hashName the hashing algorithm, 'sha-256' * * @returns a multihash */ static encode(data, hashName) { const hash = Hasher.hash(data, hashName); const hashCode = multiHashNameMap[hashName]; const hashPrefix = VarintEncoder.encode(hashCode); const hashLengthPrefix = VarintEncoder.encode(hash.length); return TypedArrayEncoder.concat([ hashPrefix, hashLengthPrefix, hash ]); } /** * * Decodes the multihash * * @param data the multihash that has to be decoded * * @returns object with the data and the hashing algorithm */ static decode(data) { const [hashPrefix, hashPrefixByteLength] = VarintEncoder.decode(data); const withoutHashPrefix = data.slice(hashPrefixByteLength); const [, lengthPrefixByteLength] = VarintEncoder.decode(withoutHashPrefix); const withoutLengthPrefix = withoutHashPrefix.slice(lengthPrefixByteLength); if (!multiHashCodeMap[hashPrefix]) throw new Error(`Unsupported hash code 0x${hashPrefix.toString(16)}`); return { data: new Uint8Array(withoutLengthPrefix), hashName: multiHashCodeMap[hashPrefix] }; } /** * * Validates if it is a valid mulithash * * @param data the multihash that needs to be validated * * @returns a boolean whether the multihash is valid */ static isValid(data) { try { MultiHashEncoder.decode(data); return true; } catch (_e) { return false; } } }; //#endregion export { MultiHashEncoder }; //# sourceMappingURL=MultiHashEncoder.mjs.map