hash-fn.js 1.5 KB

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