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