All files Hash.ts

100% Statements 17/17
50% Branches 2/4
100% Functions 6/6
100% Lines 17/17

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 411x   1x 1x   1x         3x 3x 3x       1x 1x       4x 4x       1x       2x 2x         5x 5x 5x    
import crypto, { randomBytes } from "crypto";
 
const ALGORITHM = "sha256";
const DELIMITER = "#";
 
export class HashValue {
  salt: string;
  hash: string;
 
  static makeFromPlainText(plainText: string): HashValue {
    const salt = randomBytes(16).toString("hex");
    const hash = createHash(plainText, salt);
    return new HashValue(salt, hash);
  }
 
  static makeFromSerializedText(serializedText: string): HashValue {
    const splited = serializedText.split(DELIMITER);
    return new HashValue(splited[0] || "", splited[1] || "");
  }
 
  constructor(salt: string, hash: string) {
    this.salt = salt;
    this.hash = hash;
  }
 
  serialize(): string {
    return this.salt + DELIMITER + this.hash;
  }
 
  isMatch(plainText: string): boolean {
    const hash = createHash(plainText, this.salt);
    return this.hash === hash;
  }
}
 
function createHash(plainText: string, salt: string): string {
  const hash = crypto.createHash(ALGORITHM);
  hash.update(salt + plainText);
  return hash.digest("hex");
}