ethers.js/packages/sha2/src.ts/browser.ts

37 lines
1.1 KiB
TypeScript
Raw Normal View History

2019-05-15 01:25:46 +03:00
"use strict";
import * as hash from "hash.js";
import { arrayify, BytesLike } from "@ethersproject/bytes";
2019-08-02 01:04:06 +03:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
2019-05-15 01:25:46 +03:00
export enum SupportedAlgorithm { sha256 = "sha256", sha512 = "sha512" };
2019-05-15 01:25:46 +03:00
export function ripemd160(data: BytesLike): string {
return "0x" + (hash.ripemd160().update(arrayify(data)).digest("hex"));
}
export function sha256(data: BytesLike): string {
return "0x" + (hash.sha256().update(arrayify(data)).digest("hex"));
}
export function sha512(data: BytesLike): string {
return "0x" + (hash.sha512().update(arrayify(data)).digest("hex"));
}
export function computeHmac(algorithm: SupportedAlgorithm, key: BytesLike, data: BytesLike): string {
if (!SupportedAlgorithm[algorithm]) {
2019-08-02 01:04:06 +03:00
logger.throwError("unsupported algorithm " + algorithm, Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-15 01:25:46 +03:00
operation: "hmac",
algorithm: algorithm
});
}
return "0x" + hash.hmac((<any>hash)[algorithm], arrayify(key)).update(arrayify(data)).digest("hex");
2019-05-15 01:25:46 +03:00
}