37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
import * as plugins from './isohash.plugins.js';
|
|
|
|
const hex = (buffer: ArrayBuffer) => {
|
|
const hexCodes: string[] = [];
|
|
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) {
|
|
const smarthashModule: typeof import('@pushrocks/smarthash') = await smartenv.getSafeNodeModule('@pushrocks/smarthash');
|
|
const result = await smarthashModule.sha256FromString(stringArg);
|
|
return result;
|
|
}
|
|
}; |