crypto#randomBytes TypeScript Examples

The following examples show how to use crypto#randomBytes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From AIPerf with MIT License 7 votes vote down vote up
/**
 * Generate a unique string by length
 * @param len length of string
 * @returns a unique string
 */
function uniqueString(len: number): string {
    if (len === 0) {
        return '';
    }
    const byteLength: number = Math.ceil((Math.log2(52) + Math.log2(62) * (len - 1)) / 8);
    let num: number = randomBytes(byteLength).reduce((a: number, b: number) => a * 256 + b, 0);
    const codes: number[] = [];
    codes.push(charMap(num % 52));
    num = Math.floor(num / 52);
    for (let i: number = 1; i < len; i++) {
        codes.push(charMap(num % 62));
        num = Math.floor(num / 62);
    }

    return String.fromCharCode(...codes);
}
Example #2
Source File: utils.ts    From posthog-foss with MIT License 7 votes vote down vote up
constructor(unixTimeMs?: number) {
        if (!unixTimeMs) {
            unixTimeMs = DateTime.utc().toMillis()
        }
        let unixTimeMsBig = BigInt(unixTimeMs)
        let series = UUIDT.getSeries(unixTimeMs)
        // 64 bits (8 bytes) total
        const array = new Uint8Array(16)
        // 48 bits for time, WILL FAIL in 10 895 CE
        // XXXXXXXX-XXXX-****-****-************
        for (let i = 5; i >= 0; i--) {
            array[i] = Number(unixTimeMsBig & 0xffn) // use last 8 binary digits to set UUID 2 hexadecimal digits
            unixTimeMsBig >>= 8n // remove these last 8 binary digits
        }
        // 16 bits for series
        // ********-****-XXXX-****-************
        for (let i = 7; i >= 6; i--) {
            array[i] = series & 0xff // use last 8 binary digits to set UUID 2 hexadecimal digits
            series >>>= 8 // remove these last 8 binary digits
        }
        // 64 bits for random gibberish
        // ********-****-****-XXXX-XXXXXXXXXXXX
        array.set(randomBytes(8), 8)
        super(array)
    }
Example #3
Source File: utils.ts    From eufy-security-client with MIT License 7 votes vote down vote up
generateAdvancedLockAESKey = (): string => {
    const randomBytesArray = [...randomBytes(16)];
    let result = "";
    for(let pos = 0; pos < randomBytesArray.length; pos++) {
        result += "0123456789ABCDEF".charAt((randomBytesArray[pos] >> 4) & 15);
        result += "0123456789ABCDEF".charAt(randomBytesArray[pos] & 15);
    }
    return result;
}
Example #4
Source File: utils.ts    From DefinitelyTyped-tools with MIT License 7 votes vote down vote up
export function shuffle<T>(array: readonly T[]): T[] {
  const output = array.slice();
  let counter = output.length;
  while (counter > 0) {
    const index = Math.floor((randomBytes(1).readUInt8(0) / 2 ** 8) * counter);
    counter--;
    const elem = output[counter];
    output[counter] = output[index];
    output[index] = elem;
  }

  return output;
}
Example #5
Source File: utils.ts    From solana-solidity.js with Apache License 2.0 7 votes vote down vote up
/**
 * Create a Program Derived Address from a program ID and a random seed
 *
 * @param program Program ID to derive the PDA using
 *
 * @return PDA and the seed used to derive it
 */
export async function createProgramDerivedAddress(program: PublicKey): Promise<ProgramDerivedAddress> {
    // eslint-disable-next-line no-constant-condition
    while (true) {
        const seed = randomBytes(7);

        let address: PublicKey;
        try {
            address = await PublicKey.createProgramAddress([seed], program);

        } catch (error) {
            // If a valid PDA can't be found using the seed, generate another and try again
            continue;
        }

        return { address, seed };
    }
}
Example #6
Source File: s3-queue.ts    From posthog-foss with MIT License 6 votes vote down vote up
async enqueue(retry: EnqueuedJob): Promise<void> {
        if (!this.s3Wrapper) {
            throw new Error('S3 object not initialized')
        }
        const date = new Date(retry.timestamp).toISOString()
        const [day, time] = date.split('T')
        const dayTime = `${day.split('-').join('')}-${time.split(':').join('')}`
        const suffix = randomBytes(8).toString('hex')

        await this.s3Wrapper.upload({
            Bucket: this.serverConfig.JOB_QUEUE_S3_BUCKET_NAME,
            Key: `${this.serverConfig.JOB_QUEUE_S3_PREFIX || ''}${day}/${dayTime}-${suffix}.json.gz`,
            Body: gzipSync(Buffer.from(JSON.stringify(retry), 'utf8')),
        })
    }
Example #7
Source File: util.ts    From captcha-canvas with Apache License 2.0 6 votes vote down vote up
export function randomText(characters: number): string {
    return randomBytes(characters).toString('hex').toUpperCase().substr(0, characters);
}
Example #8
Source File: decoder.test.ts    From useDApp with MIT License 6 votes vote down vote up
describe('Multicall decoder', () => {
  const testData: [number, string[]] = [
    1,
    Array.from(Array(20).keys()).map((i) => '0x' + randomBytes((i + 1) * 8).toString('hex')),
  ]
  const encoded = ethersAbi.encodeFunctionResult('aggregate', testData)

  it('Properly decodes', () => {
    const manual = decodeAggregate(encoded)
    expect(manual).to.deep.eq(testData)
  })

  it('bench ethers', () => {
    formatBench(
      bench(() => {
        ethersAbi.decodeFunctionResult('aggregate', encoded)
      })
    )
  })

  it('bench manual', () => {
    formatBench(
      bench(() => {
        decodeAggregate(encoded)
      })
    )
  })
})
Example #9
Source File: setupTests.tsx    From prism-frontend with MIT License 6 votes vote down vote up
// eslint-disable-next-line fp/no-mutating-methods
Object.defineProperty(global.self, 'crypto', {
  value: {
    getRandomValues: <T extends ArrayBufferView | null>(arr: T) => {
      if (!arr) {
        return arr;
      }

      return randomBytes(arr.buffer.byteLength);
    },
  },
});
Example #10
Source File: crypto.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
weapi = (
  object: Record<string, number | string | boolean>
): { params: string; encSecKey: string } => {
  const text = JSON.stringify(object);
  const secretKey = randomBytes(16).map((n) =>
    base62.charAt(n % 62).charCodeAt(0)
  );
  return {
    params: aesEncrypt(
      Buffer.from(
        aesEncrypt(Buffer.from(text), "cbc", presetKey, iv).toString("base64")
      ),
      "cbc",
      secretKey,
      iv
    ).toString("base64"),
    encSecKey: rsaEncrypt(secretKey.reverse()).toString("hex"),
  };
}
Example #11
Source File: input-validation.test.ts    From n-digit-token with MIT License 6 votes vote down vote up
test('token generation algorithm validates custom byte stream option correctly', () => {
    const noParamsFunction = (): Buffer => {
        return Buffer;
    };
    const invalidParamsFunction = (length: string): Buffer => {
        return Buffer;
    };
    const invalidVoidFunction = (length: number): void => {};
    const invalidReturnFunction = (length: number): string => {
        return '';
    };

    expect(() => {
        generateSecureToken(16, { customByteStream: 'a' });
    }).toThrow(new Error('Invalid options: customByteStream must be a function that returns a byte Buffer.'));

    expect(() => {
        generateSecureToken(16, { customByteStream: true });
    }).toThrow(new Error('Invalid options: customByteStream must be a function that returns a byte Buffer.'));

    expect(() => {
        generateSecureToken(16, { customByteStream: noParamsFunction });
    }).toThrow();

    expect(() => {
        generateSecureToken(16, { customByteStream: invalidParamsFunction });
    }).toThrow();

    expect(() => {
        generateSecureToken(16, { customByteStream: invalidVoidFunction });
    }).toThrow();

    expect(() => {
        generateSecureToken(16, { customByteStream: invalidReturnFunction });
    }).toThrow();

    const token = generateSecureToken(16, { customByteStream: randomBytes });
    expect(token.length).toStrictEqual(16);
});
Example #12
Source File: TestDatabases.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Returns a fresh, unique, empty logical database on an instance of the
   * given database ID platform.
   *
   * @param id - The ID of the database platform to use, e.g. 'POSTGRES_13'
   * @returns A `Knex` connection object
   */
  async init(id: TestDatabaseId): Promise<Knex> {
    const properties = allDatabases[id];
    if (!properties) {
      const candidates = Object.keys(allDatabases).join(', ');
      throw new Error(
        `Unknown test database ${id}, possible values are ${candidates}`,
      );
    }
    if (!this.supportedIds.includes(id)) {
      const candidates = this.supportedIds.join(', ');
      throw new Error(
        `Unsupported test database ${id} for this environment, possible values are ${candidates}`,
      );
    }

    let instance: Instance | undefined = this.instanceById.get(id);

    // Ensure that a testcontainers instance is up for this ID
    if (!instance) {
      instance = await this.initAny(properties);
      this.instanceById.set(id, instance);
    }

    // Ensure that a unique logical database is created in the instance
    const connection = await instance.databaseManager
      .forPlugin(`db${randomBytes(16).toString('hex')}`)
      .getClient();

    instance.connections.push(connection);

    return connection;
  }
Example #13
Source File: api-keys.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
generate = wrapHandler(async (event) => {
  await connectToDatabase();
  const key = randomBytes(16).toString('hex');
  // Store a hash of the API key instead of the key itself
  let apiKey = await ApiKey.create({
    hashedKey: createHash('sha256').update(key).digest('hex'),
    lastFour: key.substr(-4),
    user: { id: getUserId(event) }
  });
  apiKey = await apiKey.save();
  return {
    statusCode: 200,
    body: JSON.stringify({ ...apiKey, key: key })
  };
})
Example #14
Source File: osu.ts    From project-loved-web with MIT License 6 votes vote down vote up
export function redirectToAuth(
  request: ExpressRequest,
  response: ExpressResponse,
  scopes: OsuApiScopes,
): void {
  request.session.authState = Buffer.concat([
    randomBytes(8),
    Buffer.from(JSON.stringify(scopes)),
  ]).toString('base64url');
  request.session.authBackUrl =
    typeof request.query.back === 'string' ? request.query.back : request.get('Referrer');

  response.redirect(
    `${config.osuBaseUrlExternal}/oauth/authorize?` +
      qs.stringify({
        client_id: config.osuClientId,
        redirect_uri: config.osuClientRedirect,
        response_type: 'code',
        scope: scopes.join(' '),
        state: request.session.authState,
      }),
  );
}
Example #15
Source File: CourseGuest.ts    From backend with MIT License 6 votes vote down vote up
export async function generateNewCourseGuestToken(manager: EntityManager): Promise<string> {
    let token;
    do {
        token = randomBytes(48).toString("hex");
    }
    while (await manager.findOne(CourseGuest, {
        where: {
            token: token
        }
    }));

    return token;
}
Example #16
Source File: utils.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function setProcessEnv() {
  process.env.TEST_RUN_ID =
    process.env.TEST_RUN_ID ?? `id${randomBytes(16).toString('hex')}g`;
  process.env.PLATFORM_ENV = process.env.PLATFORM_ENV?.toLowerCase() || '';
  process.env.PLATFORM_HOST = getPlatformHost(process.env.PLATFORM_ENV);
  setCliExecPath();
}
Example #17
Source File: channel.ts    From nice-grpc with MIT License 6 votes vote down vote up
test('waitForChannelReady deadline', async () => {
  const address = `${randomBytes(16).toString('hex')}:80`;

  const channel = createChannel(address);
  await expect(
    waitForChannelReady(channel, new Date(Date.now() + 1000)),
  ).rejects.toMatchInlineSnapshot(
    `[Error: Deadline passed without connectivity state change]`,
  );

  channel.close();
});
Example #18
Source File: logsManager.ts    From remix-project with MIT License 6 votes vote down vote up
newFilter (filterType, params) {
    const filterId = '0x' + randomBytes(16).toString('hex')
    if (filterType === 'block' || filterType === 'pendingTransactions') {
      this.filters[filterId] = { filterType }
    }
    if (filterType === 'filter') {
      this.filters[filterId] = { filterType, params }
    }
    this.filterTracking[filterId] = {}
    return filterId
  }
Example #19
Source File: utils.spec.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Synchronous function to sample PeerIds
 * @returns a PeerId
 */
export function createPeerId(): PeerId {
  return privKeyToPeerId(u8aToHex(randomBytes(32)))
}
Example #20
Source File: AppUpdater.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
private async getOrCreateStagingUserId(): Promise<string> {
    const file = path.join(this.app.userDataPath, ".updaterId");
    try {
      const id = await readFile(file, "utf-8");
      if (UUID.check(id)) {
        return id;
      } else {
        this._logger.warn(
          `Staging user id file exists, but content was invalid: ${id}`
        );
      }
    } catch (e) {
      if (e.code !== "ENOENT") {
        this._logger.warn(
          `Couldn't read staging user ID, creating a blank one: ${e}`
        );
      }
    }

    const id = UUID.v5(randomBytes(4096), UUID.OID);
    this._logger.info(`Generated new staging user ID: ${id}`);
    try {
      await outputFile(file, id);
    } catch (e) {
      this._logger.warn(`Couldn't write out staging user ID: ${e}`);
    }
    return id;
  }
Example #21
Source File: end-node-otaa.ts    From lorawan-node-simulator with MIT License 6 votes vote down vote up
public getJoinRequestPacket(): LoraPacket {
        let packet = lora_packet.fromFields({
            MType: 'Join Request',
            AppEUI: this._appEUI,
            DevEUI: this._devEUI,
            DevNonce: randomBytes(2)
        })

        return packet;
    }
Example #22
Source File: faker.utils.ts    From rest-api.ts with MIT License 6 votes vote down vote up
export function randomString(size: number = 8): string {
  return randomBytes(size).toString('hex');
}
Example #23
Source File: helper.ts    From bbs-signatures with Apache License 2.0 6 votes vote down vote up
generateMessages = (
  numberOfMessages: number,
  messageSizeInBytes: number
): Uint8Array[] => {
  const coder = new Coder();
  const messages: Uint8Array[] = [];
  for (let i = 0; i < numberOfMessages; i++) {
    messages[i] = randomBytes(messageSizeInBytes);
  }
  return messages;
}
Example #24
Source File: ape-key.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
export async function generateApeKey(
  req: MonkeyTypes.Request
): Promise<MonkeyResponse> {
  const { name, enabled } = req.body;
  const { uid } = req.ctx.decodedToken;
  const { maxKeysPerUser, apeKeyBytes, apeKeySaltRounds } =
    req.ctx.configuration.apeKeys;

  const currentNumberOfApeKeys = await ApeKeysDAL.countApeKeysForUser(uid);

  if (currentNumberOfApeKeys >= maxKeysPerUser) {
    throw new MonkeyError(409, "Maximum number of ApeKeys have been generated");
  }

  const apiKey = randomBytes(apeKeyBytes).toString("base64url");
  const saltyHash = await hash(apiKey, apeKeySaltRounds);

  const apeKey: MonkeyTypes.ApeKey = {
    _id: new ObjectId(),
    name,
    enabled,
    uid,
    hash: saltyHash,
    createdOn: Date.now(),
    modifiedOn: Date.now(),
    lastUsedOn: -1,
    useCount: 0,
  };

  const apeKeyId = await ApeKeysDAL.addApeKey(apeKey);

  return new MonkeyResponse("ApeKey generated", {
    apeKey: base64UrlEncode(`${apeKeyId}.${apiKey}`),
    apeKeyId,
    apeKeyDetails: cleanApeKey(apeKey),
  });
}
Example #25
Source File: test-utils.ts    From office-booker with MIT License 6 votes vote down vote up
getNormalUser = () => `${randomBytes(10).toString('hex')}@office-booker.test`
Example #26
Source File: generate-keys.ts    From server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a Random IV and Secret
 *
 * @returns {Object} - Contains iv and secret key
 */
export default function (): IRandomKeys {
  const iv = randomBytes(16);
  const secret = randomBytes(32);
  return {
    iv: iv.toString('hex'),
    secret: secret.toString('hex'),
  };
}
Example #27
Source File: Utils.ts    From wa-sticker-formatter with MIT License 5 votes vote down vote up
static generateStickerID = (): string => randomBytes(32).toString('hex')
Example #28
Source File: server.ts    From Assistive-Webdriver with MIT License 5 votes vote down vote up
createId = () => randomBytes(32).toString("hex")
Example #29
Source File: horizon-apis.service.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
addHorizonApi(params: Omit<IHorizonApi, '_id' | 'Server'>): void {
    const recordId = randomBytes(16).toString('hex');
    this.horizonApisStore.upsert(recordId, createHorizonApi({ _id: recordId, ...params }));
  }