Blame view

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