Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80537 views
1
var test = require('tape')
2
var crypto = require('../')
3
var randomBytes = require('randombytes')
4
var randomBytesFunctions = {
5
randomBytes: randomBytes,
6
pseudoRandomBytes: crypto.pseudoRandomBytes
7
}
8
for (var randomBytesName in randomBytesFunctions) {
9
// Both randomBytes and pseudoRandomBytes should provide the same interface
10
var randomBytes = randomBytesFunctions[randomBytesName];
11
test('get error message', function (t) {
12
13
try {
14
var b = randomBytes(10)
15
t.ok(Buffer.isBuffer(b))
16
t.end()
17
} catch (err) {
18
t.ok(/not supported/.test(err.message), '"not supported" is in error message')
19
t.end()
20
}
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
38
var L = 1000
39
var b = randomBytes(L)
40
41
var mean = [].reduce.call(b, function (a, b) { return a + b}, 0) / L
42
43
// test that the random numbers are plausably random.
44
// Math.random() will pass this, but this will catch
45
// terrible mistakes such as this blunder:
46
// https://github.com/dominictarr/crypto-browserify/commit/3267955e1df7edd1680e52aeede9a89506ed2464#commitcomment-7916835
47
48
// this doesn't check that the bytes are in a random *order*
49
// but it's better than nothing.
50
51
var expected = 256/2
52
var smean = Math.sqrt(mean)
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
})
61
}
62
63
64