index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Load modules
  2. var Lab = require('lab');
  3. var Cryptiles = require('../lib');
  4. // Declare internals
  5. var internals = {};
  6. // Test shortcuts
  7. var expect = Lab.expect;
  8. var before = Lab.before;
  9. var after = Lab.after;
  10. var describe = Lab.experiment;
  11. var it = Lab.test;
  12. describe('Cryptiles', function () {
  13. describe('#randomString', function () {
  14. it('should generate the right length string', function (done) {
  15. for (var i = 1; i <= 1000; ++i) {
  16. expect(Cryptiles.randomString(i).length).to.equal(i);
  17. }
  18. done();
  19. });
  20. it('returns an error on invalid bits size', function (done) {
  21. expect(Cryptiles.randomString(99999999999999999999).message).to.equal('Failed generating random bits: Argument #1 must be number > 0');
  22. done();
  23. });
  24. });
  25. describe('#randomBits', function () {
  26. it('returns an error on invalid input', function (done) {
  27. expect(Cryptiles.randomBits(0).message).to.equal('Invalid random bits count');
  28. done();
  29. });
  30. });
  31. describe('#fixedTimeComparison', function () {
  32. var a = Cryptiles.randomString(50000);
  33. var b = Cryptiles.randomString(150000);
  34. it('should take the same amount of time comparing different string sizes', function (done) {
  35. var now = Date.now();
  36. Cryptiles.fixedTimeComparison(b, a);
  37. var t1 = Date.now() - now;
  38. now = Date.now();
  39. Cryptiles.fixedTimeComparison(b, b);
  40. var t2 = Date.now() - now;
  41. expect(t2 - t1).to.be.within(-20, 20);
  42. done();
  43. });
  44. it('should return true for equal strings', function (done) {
  45. expect(Cryptiles.fixedTimeComparison(a, a)).to.equal(true);
  46. done();
  47. });
  48. it('should return false for different strings (size, a < b)', function (done) {
  49. expect(Cryptiles.fixedTimeComparison(a, a + 'x')).to.equal(false);
  50. done();
  51. });
  52. it('should return false for different strings (size, a > b)', function (done) {
  53. expect(Cryptiles.fixedTimeComparison(a + 'x', a)).to.equal(false);
  54. done();
  55. });
  56. it('should return false for different strings (size, a = b)', function (done) {
  57. expect(Cryptiles.fixedTimeComparison(a + 'x', a + 'y')).to.equal(false);
  58. done();
  59. });
  60. it('should return false when not a string', function (done) {
  61. expect(Cryptiles.fixedTimeComparison('x', null)).to.equal(false);
  62. done();
  63. });
  64. });
  65. });