random-bytes.js 1.8 KB

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