random-fill.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. var test = require('tape');
  3. var crypto = require('../');
  4. var Buffer = require('safe-buffer').Buffer;
  5. test('get error message', function (t) {
  6. try {
  7. var b = crypto.randomFillSync(Buffer.alloc(10));
  8. t.ok(Buffer.isBuffer(b));
  9. t.end();
  10. } catch (err) {
  11. t.ok((/not supported/).test(err.message), '"not supported" is in error message');
  12. t.end();
  13. }
  14. });
  15. test('randomfill', function (t) {
  16. t.plan(5);
  17. t.equal(crypto.randomFillSync(Buffer.alloc(10)).length, 10);
  18. t.ok(Buffer.isBuffer(crypto.randomFillSync(Buffer.alloc(10))));
  19. crypto.randomFill(Buffer.alloc(10), function (ex, bytes) {
  20. t.error(ex);
  21. t.equal(bytes.length, 10);
  22. t.ok(Buffer.isBuffer(bytes));
  23. t.end();
  24. });
  25. });
  26. test('seems random', function (t) {
  27. var L = 1000;
  28. var buffer = crypto.randomFillSync(Buffer.alloc(L));
  29. var mean = Array.prototype.reduce.call(buffer, function (a, b) {
  30. return a + b;
  31. }, 0) / L;
  32. // test that the random numbers are plausably random.
  33. // Math.random() will pass this, but this will catch
  34. // terrible mistakes such as this blunder:
  35. // https://github.com/browserify/crypto-browserify/commit/3267955e1df7edd1680e52aeede9a89506ed2464#commitcomment-7916835
  36. // this doesn't check that the bytes are in a random *order*
  37. // but it's better than nothing.
  38. var expected = 256 / 2;
  39. var smean = Math.sqrt(mean);
  40. // console.log doesn't work right on testling, *grumble grumble*
  41. console.log(JSON.stringify([expected - smean, mean, expected + smean]));
  42. t.ok(mean < expected + smean);
  43. t.ok(mean > expected - smean);
  44. t.end();
  45. });