Skip to content

Instantly share code, notes, and snippets.

@rictorres
Created May 22, 2018 19:46
Show Gist options
  • Save rictorres/70e46e37b6955a3d7de4256c222b7c06 to your computer and use it in GitHub Desktop.
Save rictorres/70e46e37b6955a3d7de4256c222b7c06 to your computer and use it in GitHub Desktop.

Revisions

  1. rictorres created this gist May 22, 2018.
    28 changes: 28 additions & 0 deletions safe-string-compare.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    'use strict'

    const crypto = require('crypto')

    /**
    * Do a constant time string comparison. Always compare the complete strings
    * against each other to get a constant time. This method does not short-cut
    * if the two string's length differs.
    *
    * @param {string} a
    * @param {string} b
    *
    * @return {boolean}
    */
    module.exports = function(a, b) {
    const strA = String(a)
    const strB = String(b)

    const len = Math.max(Buffer.byteLength(strA), Buffer.byteLength(strB))

    const bufA = Buffer.alloc(len, 0, 'utf8')
    bufA.write(strA)

    const bufB = Buffer.alloc(len, 0, 'utf8')
    bufB.write(strB)

    return crypto.timingSafeEqual(bufA, bufB)
    }