a zip code crypto-currency system good for red ONLY

index.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Load modules
  2. var Crypto = require('crypto');
  3. var Boom = require('boom');
  4. // Declare internals
  5. var internals = {};
  6. // Generate a cryptographically strong pseudo-random data
  7. exports.randomString = function (size) {
  8. var buffer = exports.randomBits((size + 1) * 6);
  9. if (buffer instanceof Error) {
  10. return buffer;
  11. }
  12. var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
  13. return string.slice(0, size);
  14. };
  15. exports.randomBits = function (bits) {
  16. if (!bits ||
  17. bits < 0) {
  18. return Boom.internal('Invalid random bits count');
  19. }
  20. var bytes = Math.ceil(bits / 8);
  21. try {
  22. return Crypto.randomBytes(bytes);
  23. }
  24. catch (err) {
  25. return Boom.internal('Failed generating random bits: ' + err.message);
  26. }
  27. };
  28. // Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match)
  29. exports.fixedTimeComparison = function (a, b) {
  30. if (typeof a !== 'string' ||
  31. typeof b !== 'string') {
  32. return false;
  33. }
  34. var mismatch = (a.length === b.length ? 0 : 1);
  35. if (mismatch) {
  36. b = a;
  37. }
  38. for (var i = 0, il = a.length; i < il; ++i) {
  39. var ac = a.charCodeAt(i);
  40. var bc = b.charCodeAt(i);
  41. mismatch |= (ac ^ bc);
  42. }
  43. return (mismatch === 0);
  44. };