brorand.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var r;
  2. module.exports = function rand(len) {
  3. if (!r)
  4. r = new Rand(null);
  5. return r.generate(len);
  6. };
  7. function Rand(rand) {
  8. this.rand = rand;
  9. }
  10. module.exports.Rand = Rand;
  11. Rand.prototype.generate = function generate(len) {
  12. return this._rand(len);
  13. };
  14. // Emulate crypto API using randy
  15. Rand.prototype._rand = function _rand(n) {
  16. console.log(this);
  17. if (this.rand.getBytes)
  18. return this.rand.getBytes(n);
  19. var res = new Uint8Array(n);
  20. for (var i = 0; i < res.length; i++)
  21. res[i] = this.rand.getByte();
  22. return res;
  23. };
  24. if (typeof self === 'object') {
  25. Rand.prototype._rand = function _rand(n) {
  26. var list = [];
  27. for (var i = 0; i < n; i++) {
  28. list.push(Math.ceil(Math.random() * 255))
  29. }
  30. var arr = new Uint8Array(list);
  31. return arr;
  32. };
  33. } else {
  34. // Node.js or Web worker with no crypto support
  35. try {
  36. var crypto = require('crypto');
  37. if (typeof crypto.randomBytes !== 'function')
  38. throw new Error('Not supported');
  39. Rand.prototype._rand = function _rand(n) {
  40. return crypto.randomBytes(n);
  41. };
  42. } catch (e) {
  43. }
  44. }