hash-fn.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { inputToArray, defaultHashLength } from '../base/hash-fn.js';
  2. import { hash as rawHash, create_derive as createDerive, create_keyed as createKeyed, } from '../../dist/wasm/nodejs/blake3_js.js';
  3. /**
  4. * @hidden
  5. */
  6. export const normalizeInput = (input, encoding) => inputToArray(typeof input === 'string' ? Buffer.from(input, encoding) : input);
  7. /**
  8. * Returns a blake3 hash of the input, returning the binary hash data.
  9. */
  10. export function hash(input, { length = defaultHashLength } = {}) {
  11. const result = Buffer.alloc(length);
  12. rawHash(normalizeInput(input), result);
  13. return result;
  14. }
  15. /**
  16. * Given cryptographic key material and a context string, services a subkey of
  17. * any length. See {@link https://docs.rs/blake3/0.1.3/blake3/fn.derive_key.html}
  18. * for more information.
  19. */
  20. export function deriveKey(context, material, { length = defaultHashLength } = {}) {
  21. const derive = createDerive(context);
  22. derive.update(normalizeInput(material));
  23. const result = Buffer.alloc(length);
  24. derive.digest(result);
  25. return result;
  26. }
  27. /**
  28. * The keyed hash function. See {@link https://docs.rs/blake3/0.1.3/blake3/fn.keyed_hash.html}.
  29. */
  30. export function keyedHash(key, input, { length = defaultHashLength } = {}) {
  31. if (key.length !== 32) {
  32. throw new Error(`key provided to keyedHash must be 32 bytes, got ${key.length}`);
  33. }
  34. const derive = createKeyed(key);
  35. derive.update(normalizeInput(input));
  36. const result = Buffer.alloc(length);
  37. derive.digest(result);
  38. return result;
  39. }
  40. //# sourceMappingURL=hash-fn.js.map