isohash/ts/index.ts

37 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-03-24 12:12:59 +00:00
import * as plugins from './isohash.plugins.js';
2020-09-29 16:21:56 +00:00
const hex = (buffer: ArrayBuffer) => {
2023-04-11 16:46:15 +00:00
const hexCodes: string[] = [];
2020-09-29 16:21:56 +00:00
const view = new DataView(buffer);
for (let i = 0; i < view.byteLength; i += 4) {
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
const value = view.getUint32(i);
// toString(16) will give the hex representation of the number without padding
const stringValue = value.toString(16);
// We use concatenation and slice for padding
const padding = '00000000';
const paddedValue = (padding + stringValue).slice(-padding.length);
hexCodes.push(paddedValue);
}
// Join all the hex strings into one
return hexCodes.join("");
};
/**
* Computes sha256 Hash from String
*/
export const sha256FromString = async (stringArg: string): Promise<string> => {
const smartenv = new plugins.smartenv.Smartenv();
if (smartenv.isBrowser) {
// Get the string as arraybuffer.
const buffer = (new TextEncoder()).encode(stringArg);
const hash = await crypto.subtle.digest("SHA-256", buffer);
const result = hex(hash);
return result;
} else if (smartenv.isNode) {
2024-05-28 10:40:32 +00:00
const smarthashModule: typeof import('@push.rocks/smarthash') = await smartenv.getSafeNodeModule('@push.rocks/smarthash');
2020-09-29 16:21:56 +00:00
const result = await smarthashModule.sha256FromString(stringArg);
return result;
}
};