2019-05-14 18:25:46 -04:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
import { createHash, createHmac } from 'crypto';
|
|
|
|
|
|
|
|
import { arrayify, BytesLike } from '@ethersproject/bytes';
|
|
|
|
|
2019-08-03 01:05:39 -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" + createHash("ripemd160").update(Buffer.from(arrayify(data))).digest("hex")
|
|
|
|
}
|
|
|
|
|
|
|
|
export function sha256(data: BytesLike): string {
|
|
|
|
return "0x" + createHash("sha256").update(Buffer.from(arrayify(data))).digest("hex")
|
|
|
|
}
|
|
|
|
|
|
|
|
export function sha512(data: BytesLike): string {
|
|
|
|
return "0x" + createHash("sha512").update(Buffer.from(arrayify(data))).digest("hex")
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-01-20 19:29:06 -05:00
|
|
|
export function computeHmac(algorithm: SupportedAlgorithm, key: BytesLike, data: BytesLike): string {
|
2020-07-13 06:48:33 -04:00
|
|
|
/* istanbul ignore if */
|
2020-01-20 19:29:06 -05:00
|
|
|
if (!SupportedAlgorithm[algorithm]) {
|
2019-08-03 01:05:39 -04:00
|
|
|
logger.throwError("unsupported algorithm - " + algorithm, Logger.errors.UNSUPPORTED_OPERATION, {
|
2019-05-14 18:25:46 -04:00
|
|
|
operation: "computeHmac",
|
|
|
|
algorithm: algorithm
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return "0x" + createHmac(algorithm, Buffer.from(arrayify(key))).update(Buffer.from(arrayify(data))).digest("hex");
|
|
|
|
}
|
|
|
|
|