fcoin/lib/crypto/ccmp.js
Christopher Jeffrey d4cc22e1c5
refactor: crypto.
2017-06-27 07:27:53 -07:00

40 lines
856 B
JavaScript

/*!
* ccmp.js - constant-time compare for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* memcmp in constant time (can only return true or false).
* This protects us against timing attacks when
* comparing an input against a secret string.
* @alias module:crypto.ccmp
* @see https://cryptocoding.net/index.php/Coding_rules
* @see `$ man 3 memcmp` (NetBSD's consttime_memequal)
* @param {Buffer} a
* @param {Buffer} b
* @returns {Boolean}
*/
module.exports = function ccmp(a, b) {
var i, res;
if (!Buffer.isBuffer(a))
return false;
if (!Buffer.isBuffer(b))
return false;
if (b.length === 0)
return a.length === 0;
res = a.length ^ b.length;
for (i = 0; i < a.length; i++)
res |= a[i] ^ b[i % b.length];
return res === 0;
};