Skip to content

Commit

Permalink
feat: computeDigestMultibase (#288)
Browse files Browse the repository at this point in the history
phanshiyu authored May 9, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 08cba76 commit 5c06193
Showing 4 changed files with 289 additions and 0 deletions.
267 changes: 267 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -99,6 +99,7 @@
"zod-to-json-schema": "^3.23.0"
},
"dependencies": {
"@aws-crypto/sha256-universal": "^5.2.0",
"@govtechsg/jsonld": "^0.1.0",
"buffer": "^6.0.3",
"cross-fetch": "^3.1.5",
20 changes: 20 additions & 0 deletions src/4.0/computeDigestMultibase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Sha256 } from "@aws-crypto/sha256-universal";
import { base58 } from "ethers/lib/utils";

/**
* Computes a SHA-256 digest of the provided data and encodes it in Base58 with a 'z' prefix,
* conforming to the Multibase encoding standard. This function is intended for generating
* a multibase-encoded multihash, specifically using SHA-2 with 256-bits of output.
* The multibase value is fixed as 'z' to match the specifications.
*
* @param {ArrayBuffer|string} data - The data to hash. This can be either a string or an ArrayBuffer.
* @returns {Promise<string>} A promise that resolves to the Base58 encoded SHA-256 hash of the input data,
* prefixed with 'z' as per the Multibase specification.
*/
export async function computeDigestMultibase(data: ArrayBuffer | string): Promise<string> {
const sha256 = new Sha256();
sha256.update(data);
const sha256Digest = await sha256.digest();
// manually prefix with 'z' as per https://w3c-ccg.github.io/multibase/#mh-registry
return `z${base58.encode(sha256Digest)}`;
}
1 change: 1 addition & 0 deletions src/4.0/exports/utils.ts
Original file line number Diff line number Diff line change
@@ -4,3 +4,4 @@ export {
isV4WrappedDocument as isWrappedDocument,
isV4SignedWrappedDocument as isSignedWrappedDocument,
} from "../types";
export { computeDigestMultibase } from "../computeDigestMultibase";

0 comments on commit 5c06193

Please sign in to comment.