hash-fn.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import native from './native.js';
  2. import { defaultHashLength } from '../base/hash-fn.js';
  3. /**
  4. * @hidden
  5. */
  6. export const normalizeInput = (input, encoding) => {
  7. if (input instanceof Buffer) {
  8. return input;
  9. }
  10. if (typeof input === 'string') {
  11. return Buffer.from(input, encoding);
  12. }
  13. return Buffer.from(input);
  14. };
  15. /**
  16. * Returns a blake3 hash of the input, returning the binary hash data.
  17. */
  18. export function hash(input, { length = defaultHashLength } = {}) {
  19. return native.hash(normalizeInput(input), length);
  20. }
  21. /**
  22. * Given cryptographic key material and a context string, services a subkey of
  23. * any length. See {@link https://docs.rs/blake3/0.1.3/blake3/fn.derive_key.html}
  24. * for more information.
  25. */
  26. export function deriveKey(context, material, { length = defaultHashLength } = {}) {
  27. const hasher = new native.Hasher(undefined, context);
  28. hasher.update(normalizeInput(material));
  29. const result = Buffer.alloc(length);
  30. hasher.digest(result);
  31. return result;
  32. }
  33. /**
  34. * The keyed hash function. See {@link https://docs.rs/blake3/0.1.3/blake3/fn.keyed_hash.html}.
  35. */
  36. export function keyedHash(key, input, { length = defaultHashLength } = {}) {
  37. const hasher = new native.Hasher(key);
  38. hasher.update(normalizeInput(input));
  39. const result = Buffer.alloc(length);
  40. hasher.digest(result);
  41. return result;
  42. }
  43. //# sourceMappingURL=hash-fn.js.map