Projekt

Obecné

Profil

Stáhnout (1.47 KB) Statistiky
| Větev: | Revize:
1 3a515b92 cagy
var r;
2
3
module.exports = function rand(len) {
4
  if (!r)
5
    r = new Rand(null);
6
7
  return r.generate(len);
8
};
9
10
function Rand(rand) {
11
  this.rand = rand;
12
}
13
module.exports.Rand = Rand;
14
15
Rand.prototype.generate = function generate(len) {
16
  return this._rand(len);
17
};
18
19
// Emulate crypto API using randy
20
Rand.prototype._rand = function _rand(n) {
21
  if (this.rand.getBytes)
22
    return this.rand.getBytes(n);
23
24
  var res = new Uint8Array(n);
25
  for (var i = 0; i < res.length; i++)
26
    res[i] = this.rand.getByte();
27
  return res;
28
};
29
30
if (typeof self === 'object') {
31
  if (self.crypto && self.crypto.getRandomValues) {
32
    // Modern browsers
33
    Rand.prototype._rand = function _rand(n) {
34
      var arr = new Uint8Array(n);
35
      self.crypto.getRandomValues(arr);
36
      return arr;
37
    };
38
  } else if (self.msCrypto && self.msCrypto.getRandomValues) {
39
    // IE
40
    Rand.prototype._rand = function _rand(n) {
41
      var arr = new Uint8Array(n);
42
      self.msCrypto.getRandomValues(arr);
43
      return arr;
44
    };
45
46
  // Safari's WebWorkers do not have `crypto`
47
  } else if (typeof window === 'object') {
48
    // Old junk
49
    Rand.prototype._rand = function() {
50
      throw new Error('Not implemented yet');
51
    };
52
  }
53
} else {
54
  // Node.js or Web worker with no crypto support
55
  try {
56
    var crypto = require('crypto');
57
    if (typeof crypto.randomBytes !== 'function')
58
      throw new Error('Not supported');
59
60
    Rand.prototype._rand = function _rand(n) {
61
      return crypto.randomBytes(n);
62
    };
63
  } catch (e) {
64
  }
65
}