index.js 971 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict'
  2. const crypto = require('crypto')
  3. const scmpCompare = require('./lib/scmpCompare')
  4. /**
  5. * Does a constant-time Buffer comparison by not short-circuiting
  6. * on first sign of non-equivalency.
  7. *
  8. * @param {Buffer} a The first Buffer to be compared against the second
  9. * @param {Buffer} b The second Buffer to be compared against the first
  10. * @return {Boolean}
  11. */
  12. module.exports = function scmp (a, b) {
  13. // check that both inputs are buffers
  14. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  15. throw new Error('Both scmp args must be Buffers')
  16. }
  17. // return early here if buffer lengths are not equal since timingSafeEqual
  18. // will throw if buffer lengths are not equal
  19. if (a.length !== b.length) {
  20. return false
  21. }
  22. // use crypto.timingSafeEqual if available (since Node.js v6.6.0),
  23. // otherwise use our own scmp-internal function.
  24. if (crypto.timingSafeEqual) {
  25. return crypto.timingSafeEqual(a, b)
  26. }
  27. return scmpCompare(a, b)
  28. }