hash-instance.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { normalizeInput } from './hash-fn.js';
  2. import { BaseHash } from '../base/index.js';
  3. import { Transform } from 'stream.js';
  4. import { getWasm } from './wasm.js';
  5. import { NodeHashReader } from './hash-reader.js';
  6. /**
  7. * @inheritdoc
  8. */
  9. export class NodeHash extends Transform {
  10. constructor(implementation, getReader) {
  11. super();
  12. this.hash = new BaseHash(implementation, l => Buffer.alloc(l), getReader);
  13. }
  14. /**
  15. * @reader
  16. */
  17. reader(options) {
  18. const reader = this.hash.reader(options);
  19. return reader;
  20. }
  21. /**
  22. * @inheritdoc
  23. */
  24. update(data, encoding) {
  25. this.hash.update(normalizeInput(data, encoding));
  26. return this;
  27. }
  28. digest(encoding, options) {
  29. let resolvedOpts;
  30. let resolvedEnc;
  31. if (encoding && typeof encoding === 'object') {
  32. resolvedOpts = encoding;
  33. resolvedEnc = undefined;
  34. }
  35. else {
  36. resolvedOpts = options;
  37. resolvedEnc = encoding;
  38. }
  39. const result = this.hash.digest(resolvedOpts);
  40. return resolvedEnc ? result.toString(resolvedEnc) : result;
  41. }
  42. /**
  43. * @inheritdoc
  44. */
  45. dispose() {
  46. this.hash.dispose();
  47. }
  48. /**
  49. * @inheritdoc
  50. * @hidden
  51. */
  52. _transform(chunk, encoding, callback) {
  53. this.update(chunk, encoding);
  54. callback();
  55. }
  56. /**
  57. * @inheritdoc
  58. * @hidden
  59. */
  60. _flush(callback) {
  61. callback(null, this.digest());
  62. }
  63. }
  64. /**
  65. * A Node.js crypto-like createHash method.
  66. */
  67. export const createHash = () => new NodeHash(getWasm().create_hasher(), r => new NodeHashReader(r));
  68. /**
  69. * Construct a new Hasher for the keyed hash function.
  70. */
  71. export const createKeyed = (key) => new NodeHash(getWasm().create_keyed(key), r => new NodeHashReader(r));
  72. /**
  73. * Construct a new Hasher for the key derivation function.
  74. */
  75. export const createDeriveKey = (context) => new NodeHash(getWasm().create_derive(context), r => new NodeHashReader(r));
  76. //# sourceMappingURL=hash-instance.js.map