UNPKG

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