All files / ethers.js/src.ts/crypto sha2.ts

100% Statements 78/78
100% Branches 12/12
100% Functions 8/8
100% Lines 78/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 791x 1x 1x 1x 1x 1x 1x 1x 77295x 77295x 1x 1x 259x 259x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 77296x 77296x 77296x 1x 1x 1x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 260x 260x 260x 1x 1x 1x 3x 2x 2x 1x  
import { createHash } from "./crypto.js";
 
import { getBytes, hexlify } from "../utils/index.js";
 
import type { BytesLike } from "../utils/index.js";
 
 
const _sha256 = function(data: Uint8Array): Uint8Array {
    return createHash("sha256").update(data).digest();
}
 
const _sha512 = function(data: Uint8Array): Uint8Array {
    return createHash("sha512").update(data).digest();
}
 
let __sha256: (data: Uint8Array) => BytesLike = _sha256;
let __sha512: (data: Uint8Array) => BytesLike = _sha512;
 
let locked256 = false, locked512 = false;
 
 
/**
 *  Compute the cryptographic SHA2-256 hash of %%data%%.
 *
 *  @_docloc: api/crypto:Hash Functions
 *  @returns DataHexstring
 *
 *  @example:
 *    sha256("0x")
 *    //_result:
 *
 *    sha256("0x1337")
 *    //_result:
 *
 *    sha256(new Uint8Array([ 0x13, 0x37 ]))
 *    //_result:
 *
 */
export function sha256(_data: BytesLike): string {
    const data = getBytes(_data, "data");
    return hexlify(__sha256(data));
}
sha256._ = _sha256;
sha256.lock = function(): void { locked256 = true; }
sha256.register = function(func: (data: Uint8Array) => BytesLike): void {
    if (locked256) { throw new Error("sha256 is locked"); }
    __sha256 = func;
}
Object.freeze(sha256);
 
 
/**
 *  Compute the cryptographic SHA2-512 hash of %%data%%.
 *
 *  @_docloc: api/crypto:Hash Functions
 *  @returns DataHexstring
 *
 *  @example:
 *    sha512("0x")
 *    //_result:
 *
 *    sha512("0x1337")
 *    //_result:
 *
 *    sha512(new Uint8Array([ 0x13, 0x37 ]))
 *    //_result:
 */
export function sha512(_data: BytesLike): string {
    const data = getBytes(_data, "data");
    return hexlify(__sha512(data));
}
sha512._ = _sha512;
sha512.lock = function(): void { locked512 = true; }
sha512.register = function(func: (data: Uint8Array) => BytesLike): void {
    if (locked512) { throw new Error("sha512 is locked"); }
    __sha512 = func;
}
Object.freeze(sha256);