random-bytes.js 1.7 KB

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