buffer_utils.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.concatKdf = exports.lengthAndInput = exports.uint32be = exports.uint64be = exports.p2s = exports.concat = exports.decoder = exports.encoder = void 0;
  4. const digest_js_1 = require("../runtime/digest.js");
  5. exports.encoder = new TextEncoder();
  6. exports.decoder = new TextDecoder();
  7. const MAX_INT32 = 2 ** 32;
  8. function concat(...buffers) {
  9. const size = buffers.reduce((acc, { length }) => acc + length, 0);
  10. const buf = new Uint8Array(size);
  11. let i = 0;
  12. buffers.forEach((buffer) => {
  13. buf.set(buffer, i);
  14. i += buffer.length;
  15. });
  16. return buf;
  17. }
  18. exports.concat = concat;
  19. function p2s(alg, p2sInput) {
  20. return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput);
  21. }
  22. exports.p2s = p2s;
  23. function writeUInt32BE(buf, value, offset) {
  24. if (value < 0 || value >= MAX_INT32) {
  25. throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
  26. }
  27. buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);
  28. }
  29. function uint64be(value) {
  30. const high = Math.floor(value / MAX_INT32);
  31. const low = value % MAX_INT32;
  32. const buf = new Uint8Array(8);
  33. writeUInt32BE(buf, high, 0);
  34. writeUInt32BE(buf, low, 4);
  35. return buf;
  36. }
  37. exports.uint64be = uint64be;
  38. function uint32be(value) {
  39. const buf = new Uint8Array(4);
  40. writeUInt32BE(buf, value);
  41. return buf;
  42. }
  43. exports.uint32be = uint32be;
  44. function lengthAndInput(input) {
  45. return concat(uint32be(input.length), input);
  46. }
  47. exports.lengthAndInput = lengthAndInput;
  48. async function concatKdf(secret, bits, value) {
  49. const iterations = Math.ceil((bits >> 3) / 32);
  50. const res = new Uint8Array(iterations * 32);
  51. for (let iter = 0; iter < iterations; iter++) {
  52. const buf = new Uint8Array(4 + secret.length + value.length);
  53. buf.set(uint32be(iter + 1));
  54. buf.set(secret, 4);
  55. buf.set(value, 4 + secret.length);
  56. res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32);
  57. }
  58. return res.slice(0, bits >> 3);
  59. }
  60. exports.concatKdf = concatKdf;