Tabnine Logo For Javascript
randomBytes
Code IndexAdd Tabnine to your IDE (free)

How to use
randomBytes
function
in
crypto

Best JavaScript code snippets using crypto.randomBytes(Showing top 15 results out of 1,845)

origin: parse-community/parse-server

// Returns a new random hex string of the given even size.
function randomHexString(size) {
 if (size === 0) {
  throw new Error('Zero-length randomHexString is useless.');
 }

 if (size % 2 !== 0) {
  throw new Error('randomHexString size must be divisible by 2.');
 }

 return (0, _crypto.randomBytes)(size / 2).toString('hex');
}
origin: GladysAssistant/Gladys

/**
 * @private
 * @description Generate a jwt secret.
 * @example
 * const jwtSecret = generateJwtSecret();
 * @returns {string} JwtSecret.
 */
function generateJwtSecret() {
 const jwtSecret = crypto
  .randomBytes(Math.ceil(JWT_SECRET_LENGTH / 2))
  .toString('hex') // convert to hexadecimal format
  .slice(0, JWT_SECRET_LENGTH); // return required number of characters

 return jwtSecret;
}
origin: tulios/kafkajs

const secureRandom = (length = 10) =>
 `${crypto.randomBytes(length).toString('hex')}-${process.pid}-${uuid()}`
origin: cube-js/cube.js

async downloadQueryResults(query, values) {
  if (!this.config.database) {
   throw new Error(`Default database should be defined to be used for temporary tables during query results downloads`);
  }
  const tableName = crypto.randomBytes(10).toString('hex');
  const columns = await this.withConnection(async db => {
   await this.setTimeZone(db);
   await db.execute(`CREATE TEMPORARY TABLE \`${this.config.database}\`.t_${tableName} AS ${query} LIMIT 0`, values);
   const result = await db.execute(`DESCRIBE \`${this.config.database}\`.t_${tableName}`);
   await db.execute(`DROP TEMPORARY TABLE \`${this.config.database}\`.t_${tableName}`);
   return result;
  });

  const types = columns.map(c => ({ name: c.Field, type: this.toGenericType(c.Type) }));

  return {
   rows: await this.query(query, values),
   types,
  };
 }
origin: tulios/kafkajs

/**
  * In cryptography, a nonce is an arbitrary number that can be used just once.
  * It is similar in spirit to a nonce * word, hence the name. It is often a random or pseudo-random
  * number issued in an authentication protocol to * ensure that old communications cannot be reused
  * in replay attacks.
  *
  * @returns {String}
  */
 static nonce() {
  return crypto
   .randomBytes(16)
   .toString('base64')
   .replace(URLSAFE_BASE64_PLUS_REGEX, '-') // make it url safe
   .replace(URLSAFE_BASE64_SLASH_REGEX, '_')
   .replace(URLSAFE_BASE64_TRAILING_EQUAL_REGEX, '')
   .toString('ascii')
 }
origin: parse-community/parse-server

// For a given config object, filename, and data, store a file
 // Returns a promise


 async createFile(filename, data, contentType, options = {}) {
  const bucket = await this._getBucket();
  const stream = await bucket.openUploadStream(filename, {
   metadata: options.metadata
  });

  if (this._fileKey !== null) {
   const iv = crypto.randomBytes(16);
   const cipher = crypto.createCipheriv(this._algorithm, this._fileKey, iv);
   const encryptedResult = Buffer.concat([cipher.update(data), cipher.final(), iv, cipher.getAuthTag()]);
   await stream.write(encryptedResult);
  } else {
   await stream.write(data);
  }

  stream.end();
  return new Promise((resolve, reject) => {
   stream.on('finish', resolve);
   stream.on('error', reject);
  });
 }
origin: cube-js/cube.js

const connectionId = crypto.randomBytes(8).toString('hex');
connectionIdToSocket[connectionId] = ws;
ws.on('message', async (message) => {
origin: clinicjs/node-clinic

  fs.writeFile(bigFilepath, crypto.randomBytes(bigFilesize), done)
 })
},
origin: parse-community/parse-server

// Returns a new random alphanumeric string of the given size.
//
// Note: to simplify implementation, the result has slight modulo bias,
// because chars length of 62 doesn't divide the number of all bytes
// (256) evenly. Such bias is acceptable for most cases when the output
// length is long enough and doesn't need to be uniform.


function randomString(size) {
 if (size === 0) {
  throw new Error('Zero-length randomString is useless.');
 }

 const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789';
 let objectId = '';
 const bytes = (0, _crypto.randomBytes)(size);

 for (let i = 0; i < bytes.length; ++i) {
  objectId += chars[bytes.readUInt8(i) % chars.length];
 }

 return objectId;
}
origin: moleculerjs/moleculer

describe("With threshold", () => {
    const broker = new ServiceBroker({ logger: false });
    const shortData = crypto.randomBytes(95);
    const longData = crypto.randomBytes(105);
origin: moleculerjs/moleculer

const pass = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const mw = Middleware(pass, "aes-256-ctr", iv);
const pass = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const mw = Middleware(pass, "aes-256-ctr", iv);
origin: moleculerjs/moleculer

it("should send splitted stream chunks", () => {
      transit.publish.mockClear();
      transit.opts.maxChunkSize = 100;
      let randomData = crypto.randomBytes(1024);
      let stream = new Stream.Readable({
        read() {}
origin: tulios/kafkajs

const secureRandom = (length = 10) => crypto.randomBytes(length).toString('hex')
origin: GladysAssistant/Gladys

/**
 * @private
 * @description Generate a jwt secret.
 * @example
 * const jwtSecret = generateJwtSecret();
 * @returns {string} JwtSecret.
 */
function generateJwtSecret() {
 const jwtSecret = crypto
  .randomBytes(Math.ceil(JWT_SECRET_LENGTH / 2))
  .toString('hex') // convert to hexadecimal format
  .slice(0, JWT_SECRET_LENGTH); // return required number of characters

 return jwtSecret;
}
origin: parse-community/parse-server

// For a given config object, filename, and data, store a file
 // Returns a promise
 async createFile(filename: string, data, contentType, options = {}) {
  const bucket = await this._getBucket();
  const stream = await bucket.openUploadStream(filename, {
   metadata: options.metadata,
  });
  if (this._fileKey !== null) {
   const iv = crypto.randomBytes(16);
   const cipher = crypto.createCipheriv(this._algorithm, this._fileKey, iv);
   const encryptedResult = Buffer.concat([
    cipher.update(data),
    cipher.final(),
    iv,
    cipher.getAuthTag(),
   ]);
   await stream.write(encryptedResult);
  } else {
   await stream.write(data);
  }
  stream.end();
  return new Promise((resolve, reject) => {
   stream.on('finish', resolve);
   stream.on('error', reject);
  });
 }
cryptorandomBytes

Most used crypto functions

  • Hash.update
  • Hash.digest
  • createHash
  • Hmac.digest
  • Hmac.update
  • Cipher.final,
  • Cipher.update,
  • Decipher.update,
  • Decipher.final,
  • createCipheriv,
  • createCipher,
  • createDecipheriv,
  • createDecipher,
  • pbkdf2,
  • publicEncrypt,
  • privateDecrypt,
  • pbkdf2Sync,
  • DecipherGCM.final

Popular in JavaScript

  • redis
    Redis client library
  • mkdirp
    Recursively mkdir, like `mkdir -p`
  • request
    Simplified HTTP request client.
  • minimatch
    a glob matcher in javascript
  • fs
  • aws-sdk
    AWS SDK for JavaScript
  • mime-types
    The ultimate javascript content-type utility.
  • node-fetch
    A light-weight module that brings window.fetch to node.js
  • crypto
  • Best IntelliJ plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJavascript Code Index
Get Tabnine for your IDE now