{"size": 1176, "ext": "js", "max_stars_repo_path": "src/SecureRandom.js", "max_stars_repo_name": "lucmir/credential-commons", "max_stars_repo_stars_event_min_datetime": "2018-11-30T05:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T00:18:44.000Z", "max_issues_repo_path": "src/SecureRandom.js", "max_issues_repo_name": "DalavanCloud/credential-commons", "max_issues_repo_issues_event_min_datetime": "2018-11-14T16:10:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T18:28:19.000Z", "max_forks_repo_path": "src/SecureRandom.js", "max_forks_repo_name": "DalavanCloud/credential-commons", "max_forks_repo_forks_event_min_datetime": "2018-11-13T20:31:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T13:55:41.000Z"}
{"max_stars_count": 33, "max_issues_count": 11, "max_forks_count": 9, "avg_line_length": 28.6829268293, "max_line_length": 78, "alphanum_fraction": 0.6284013605}
const sjcl = require('sjcl');
const logger = require('./logger');

class SecureRandom {
  constructor(seedHexString) {
    logger.debug('Init Secure Random');
    // eslint-disable-next-line new-cap
    this.sjclRandom = new sjcl.prng(10);

    if (seedHexString) {
      const seed = sjcl.codec.hex.toBits(seedHexString);
      this.sjclRandom.addEntropy(seed, undefined, 'csprng');
      this.isSeeded = true;
    } else {
      try {
        logger.debug('Trying crypto');
        /* eslint-disable global-require */
        const hexString = require('crypto').randomBytes(1024).toString('hex');
        /* eslint-enable global-require */
        const seed = sjcl.codec.hex.toBits(hexString);
        this.sjclRandom.addEntropy(seed, undefined, 'csprng');
        this.isSeeded = true;
      } catch (error) {
        logger.warn(`Crypto: ${error}`);
        this.isSeeded = false;
      }
    }
  }

  wordWith(size) {
    if (!this.isSeeded) {
      throw new Error("Can't user SecureRandom before seeding");
    }

    const randomBytes = this.sjclRandom.randomWords(size / 8, 10);
    return sjcl.codec.hex.fromBits(randomBytes);
  }
}

module.exports = SecureRandom;
