您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

random-fill.js 1.5KB

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