Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. class Arcfour {
  2. constructor(key) {
  3. this.i = 0;
  4. this.j = 0;
  5. this.S = [];
  6. let i;
  7. let j;
  8. let t;
  9. for (i = 0; i < 256; i += 1) this.S[i] = i;
  10. j = 0;
  11. for (i = 0; i < 256; i += 1) {
  12. j = (j + this.S[i] + key[i % key.length]) & 255;
  13. t = this.S[i];
  14. this.S[i] = this.S[j];
  15. this.S[j] = t;
  16. }
  17. this.i = 0;
  18. this.j = 0;
  19. }
  20.  
  21. next() {
  22. this.i = (this.i + 1) & 255;
  23. this.j = (this.j + this.S[this.i]) & 255;
  24. const t = this.S[this.i];
  25. this.S[this.i] = this.S[this.j];
  26. this.S[this.j] = t;
  27. return this.S[(t + this.S[this.i]) & 255];
  28. }
  29. }
  30.  
  31. // pseudorandom number generator
  32. class PRNG {
  33. constructor() {
  34. this.pool = [];
  35. this.pptr = 0;
  36. let t;
  37. if (global && global.crypto && global.crypto.getRandomValues) {
  38. // Use webcrypto if available
  39. const ua = new Uint8Array(32);
  40. global.crypto.getRandomValues(ua);
  41. for (t = 0; t < 32; ++t) this.pool[this.pptr++] = ua[t];
  42. }
  43. if (
  44. window.navigator.appName === 'Netscape' &&
  45. window.navigator.appVersion < '5' &&
  46. global &&
  47. global.crypto
  48. ) {
  49. // Extract entropy (256 bits) from NS4 RNG if available
  50. const z = global.crypto.random(32);
  51. for (t = 0; t < z.length; ++t) rng_pool[this.pptr++] = z.charCodeAt(t) & 255;
  52. }
  53.  
  54. while (this.pptr < 255) {
  55. // extract some randomness from Math.random()
  56. t = Math.floor(65536 * Math.random());
  57. this.pool[this.pptr++] = t >>> 8;
  58. this.pool[this.pptr++] = t & 255;
  59. }
  60. this.pptr = 0;
  61. this.seedInt(new Date().getTime());
  62. }
  63.  
  64. // Mix in a 32-bit integer into the pool
  65. seedInt(x) {
  66. this.pool[this.pptr++] ^= x & 255;
  67. this.pool[this.pptr++] ^= (x >> 8) & 255;
  68. this.pool[this.pptr++] ^= (x >> 24) & 255;
  69. this.pool[this.pptr++] ^= (x >> 16) & 255;
  70. if (this.pptr >= 255) this.pptr -= 255;
  71. }
  72.  
  73. getByte() {
  74. if (this.state == null) {
  75. this.seedInt(new Date().getTime());
  76. this.state = new Arcfour(this.pool);
  77. for (this.pptr = 0; this.pptr < this.pool.length; this.pptr += 1) this.pool[this.pptr] = 0;
  78. this.pptr = 0;
  79. // rng_pool = null;
  80. }
  81.  
  82. // TODO: allow reseeding after first request
  83. return this.state.next();
  84. }
  85.  
  86. nextBytes(ba) {
  87. for (let i = 0; i < ba.length; ++i) ba[i] = this.getByte();
  88. }
  89. }
  90.  
  91. const SecureRandom = new PRNG();
  92. document.addEventListener('mousedown', () => SecureRandom.seedInt(new Date().getTime()));
  93. export default SecureRandom;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement