// 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'); }
/** * @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; }
const secureRandom = (length = 10) => `${crypto.randomBytes(length).toString('hex')}-${process.pid}-${uuid()}`
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, }; }
/** * 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') }
// 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); }); }
const connectionId = crypto.randomBytes(8).toString('hex'); connectionIdToSocket[connectionId] = ws; ws.on('message', async (message) => {
fs.writeFile(bigFilepath, crypto.randomBytes(bigFilesize), done) }) },
// 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; }
describe("With threshold", () => { const broker = new ServiceBroker({ logger: false }); const shortData = crypto.randomBytes(95); const longData = crypto.randomBytes(105);
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);
it("should send splitted stream chunks", () => { transit.publish.mockClear(); transit.opts.maxChunkSize = 100; let randomData = crypto.randomBytes(1024); let stream = new Stream.Readable({ read() {}
const secureRandom = (length = 10) => crypto.randomBytes(length).toString('hex')
/** * @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; }
// 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); }); }