cryptoUtils.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.md5Hash = md5Hash;
  6. exports.newObjectId = newObjectId;
  7. exports.newToken = newToken;
  8. exports.randomHexString = randomHexString;
  9. exports.randomString = randomString;
  10. var _crypto = require("crypto");
  11. // Returns a new random hex string of the given even size.
  12. function randomHexString(size) {
  13. if (size === 0) {
  14. throw new Error('Zero-length randomHexString is useless.');
  15. }
  16. if (size % 2 !== 0) {
  17. throw new Error('randomHexString size must be divisible by 2.');
  18. }
  19. return (0, _crypto.randomBytes)(size / 2).toString('hex');
  20. }
  21. // Returns a new random alphanumeric string of the given size.
  22. //
  23. // Note: to simplify implementation, the result has slight modulo bias,
  24. // because chars length of 62 doesn't divide the number of all bytes
  25. // (256) evenly. Such bias is acceptable for most cases when the output
  26. // length is long enough and doesn't need to be uniform.
  27. function randomString(size) {
  28. if (size === 0) {
  29. throw new Error('Zero-length randomString is useless.');
  30. }
  31. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789';
  32. let objectId = '';
  33. const bytes = (0, _crypto.randomBytes)(size);
  34. for (let i = 0; i < bytes.length; ++i) {
  35. objectId += chars[bytes.readUInt8(i) % chars.length];
  36. }
  37. return objectId;
  38. }
  39. // Returns a new random alphanumeric string suitable for object ID.
  40. function newObjectId(size = 10) {
  41. return randomString(size);
  42. }
  43. // Returns a new random hex string suitable for secure tokens.
  44. function newToken() {
  45. return randomHexString(32);
  46. }
  47. function md5Hash(string) {
  48. return (0, _crypto.createHash)('md5').update(string).digest('hex');
  49. }
  50. //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJfY3J5cHRvIiwicmVxdWlyZSIsInJhbmRvbUhleFN0cmluZyIsInNpemUiLCJFcnJvciIsInJhbmRvbUJ5dGVzIiw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