{"id":25440249,"url":"https://github.com/diplomatiq/crypto-random","last_synced_at":"2025-07-29T06:04:37.672Z","repository":{"id":33661124,"uuid":"159065070","full_name":"Diplomatiq/crypto-random","owner":"Diplomatiq","description":"TypeScript library for generating cryptographically strong, uniformly distributed random integers from custom intervals, strings from custom character sets, and boolean values.","archived":false,"fork":false,"pushed_at":"2023-01-16T04:00:56.000Z","size":1437,"stargazers_count":4,"open_issues_count":21,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-08T12:06:09.597Z","etag":null,"topics":["cryptography","javascript","javascript-library","random-bytes","random-generation","random-int","random-string","secure-random-generator","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@diplomatiq/crypto-random","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Diplomatiq.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null}},"created_at":"2018-11-25T19:08:56.000Z","updated_at":"2021-09-09T13:03:59.000Z","dependencies_parsed_at":"2023-01-16T22:45:37.073Z","dependency_job_id":null,"html_url":"https://github.com/Diplomatiq/crypto-random","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"purl":"pkg:github/Diplomatiq/crypto-random","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diplomatiq%2Fcrypto-random","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diplomatiq%2Fcrypto-random/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diplomatiq%2Fcrypto-random/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diplomatiq%2Fcrypto-random/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Diplomatiq","download_url":"https://codeload.github.com/Diplomatiq/crypto-random/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diplomatiq%2Fcrypto-random/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267638758,"owners_count":24119764,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-29T02:00:12.549Z","response_time":2574,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cryptography","javascript","javascript-library","random-bytes","random-generation","random-int","random-string","secure-random-generator","typescript"],"created_at":"2025-02-17T11:30:03.051Z","updated_at":"2025-07-29T06:04:37.651Z","avatar_url":"https://github.com/Diplomatiq.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"logo.png\" width=\"500px\"\u003e\n\u003c/p\u003e\n\nTypeScript library for generating cryptographically strong, uniformly distributed random integers from custom intervals, strings from custom character sets, and boolean values.\n\n\u003cp\u003e\n\u003ca href=\"https://github.com/Diplomatiq/crypto-random/actions?query=workflow%3ACI\" target=\"_blank\" style=\"text-decoration: none;\"\u003e\n  \u003cimg src=\"https://github.com/Diplomatiq/crypto-random/workflows/CI/badge.svg\" alt=\"build status\"\u003e\n\u003c/a\u003e\n\n\u003ca href=\"https://github.com/Diplomatiq/crypto-random\" target=\"_blank\" style=\"text-decoration: none;\"\u003e\n  \u003cimg src=\"https://img.shields.io/github/languages/top/Diplomatiq/crypto-random.svg\" alt=\"languages used\"\u003e\n\u003c/a\u003e\n\n\u003ca href=\"https://www.npmjs.com/package/@diplomatiq/crypto-random\" target=\"_blank\" style=\"text-decoration: none;\"\u003e\n  \u003cimg src=\"https://img.shields.io/npm/dt/@diplomatiq/crypto-random.svg\" alt=\"downloads from npm\"\u003e\n\u003c/a\u003e\n\n\u003ca href=\"https://www.npmjs.com/package/@diplomatiq/crypto-random\" target=\"_blank\" style=\"text-decoration: none;\"\u003e\n  \u003cimg src=\"https://img.shields.io/npm/v/@diplomatiq/crypto-random.svg\" alt=\"latest released version on npm\"\u003e\n\u003c/a\u003e\n\n\u003ca href=\"https://github.com/Diplomatiq/crypto-random/blob/main/LICENSE\" target=\"_blank\" style=\"text-decoration: none;\"\u003e\n  \u003cimg src=\"https://img.shields.io/npm/l/@diplomatiq/crypto-random.svg\" alt=\"license\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n## Installation\n\nBeing an npm package, you can install crypto-random with the following command:\n\n```bash\nnpm install -P @diplomatiq/crypto-random\n```\n\n## Testing\n\nRun tests with the following:\n\n```bash\nnpm test\n```\n\nBesides basic input-output and format tests, the core generation logic is also tested if it correctly produces its output following a uniform distribution. These tests can fail with a minimal probability, and that's fine. The underlying default PRNGs are always considered to be cryptographically secure, so the actual randomness of the output is not tested.\n\n## Usage\n\n_Note: This package is built as an ES6 package. You will not be able to use `require()`._\n\nAfter installation, import the `RandomGenerator` class into your project, and use its async API after instantiation:\n\n```typescript\nimport { RandomGenerator } from '@diplomatiq/crypto-random';\n\n// …\n\nasync function main() {\n    const randomGenerator = new RandomGenerator();\n    const randomString = await randomGenerator.alphanumeric(32);\n    // randomString will contain a 32-character-long alphanumeric string\n}\n```\n\nFrom version 2.0, only browser environments are supported out of the box (the default entropy source being `window.crypto.getRandomValues`). But with minimal additional work, you can inject any other entropy source (e.g. for using crypto-random in a Node.js environment). For more information, see the [Using other entropy sources](#using-other-entropy-sources) section below.\n\n## API\n\nAll the API methods return Promises.\n\nThe below referenced `MAX_ALPHABET_LEN` value determines the maximum number of elements of an alphabet used for generating random values: `MAX_ALPHABET_LEN = 4294967296`.\n\n### bytes(byteCount: number): Promise\\\u003cUint8Array\u003e;\n\n```typescript\n/**\n * Returns an array of @param byteCount length filled with cryptographically strong random bytes.\n */\nbytes(byteCount: number): Promise\u003cUint8Array\u003e;\n```\n\n### integer(min: number, max: number, howMany = 1, unique = false): Promise\\\u003cnumber[]\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated positive integer between @param min and @param max,\n * inclusive.\n * The lowest possible value of @param min is 0.\n * The highest possible value of @param max is @var Number.MAX_SAFE_INTEGER.\n * The @param max - @param min + 1 \u003c= @member MAX_ALPHABET_LEN inequality must be kept true.\n *\n * If needing more than one integer at once from a given interval, use @param howMany. This will reduce the number\n * of times calling the crypto API, making the execution faster.\n *\n * If generating more than one integers with @param unique = true,\n * the generated integers will be unique in the returned set.\n */\ninteger(min: number, max: number, howMany = 1, unique = false): Promise\u003cnumber[]\u003e;\n```\n\n### string(alphabet: string, desiredLength: number, unique = false): Promise\\\u003cstring\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated string value with a @param desiredLength length\n * from a given @param alphabet.\n *\n * If generating with @param unique = true, the characters in the string will be unique.\n */\nstring(alphabet: string, desiredLength: number, unique = false): Promise\u003cstring\u003e;\n```\n\n### lowercase(desiredLength: number, unique = false): Promise\\\u003cstring\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated string with lowercase letters only.\n */\nlowercase(desiredLength: number, unique = false): Promise\u003cstring\u003e;\n```\n\n### uppercase(desiredLength: number, unique = false): Promise\\\u003cstring\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated string with uppercase letters only.\n */\nuppercase(desiredLength: number, unique = false): Promise\u003cstring\u003e;\n```\n\n### numeric(desiredLength: number, unique = false): Promise\\\u003cstring\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated string with numeric characters only.\n */\nnumeric(desiredLength: number, unique = false): Promise\u003cstring\u003e;\n```\n\n### alphabetic(desiredLength: number, unique = false): Promise\\\u003cstring\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated string with lower- and uppercase letters only.\n */\nalphabetic(desiredLength: number, unique = false): Promise\u003cstring\u003e;\n```\n\n### alphanumeric(desiredLength: number, unique = false): Promise\\\u003cstring\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated alphanumeric string.\n */\nalphanumeric(desiredLength: number, unique = false): Promise\u003cstring\u003e;\n```\n\n### boolean(): Promise\\\u003cboolean\u003e;\n\n```typescript\n/**\n * Returns a cryptographically strong randomly generated boolean value.\n */\nboolean(): Promise\u003cboolean\u003e;\n```\n\n## Entropy sources\n\n### Default entropy source\n\nProviding no arguments in the constructor, the `RandomGenerator` is instantiated using the default `BrowserEntropyProvider` as its entropy source. This will look for `window.crypto.getRandomValues`.\n\n```typescript\ntype UnsignedTypedArray = Uint8Array | Uint16Array | Uint32Array;\n```\n\n```typescript\ninterface EntropyProvider {\n    getRandomValues\u003cT extends UnsignedTypedArray\u003e(array: T): T | Promise\u003cT\u003e;\n}\n```\n\n```typescript\nclass RandomGenerator {\n    /**\n     * Provides entropy in the form of random-filled typed arrays.\n     */\n    private readonly entropyProvider: EntropyProvider;\n\n    constructor(entropyProvider: EntropyProvider = new BrowserEntropyProvider()) {\n        this.entropyProvider = entropyProvider;\n    }\n\n    // …\n}\n```\n\n### Using other entropy sources\n\nYou can inject any entropy source into the `RandomGenerator` as long as it implements the required `EntropyProvider` interface specified above.\n\nE.g. in your Node.js application, you can create `nodeJsEntropyProvider.ts`:\n\n```typescript\nimport { EntropyProvider, UnsignedTypedArray } from '@diplomatiq/crypto-random';\nimport { randomFill } from 'crypto';\n\nexport class NodeJsEntropyProvider implements EntropyProvider {\n    public async getRandomValues\u003cT extends UnsignedTypedArray\u003e(array: T): Promise\u003cT\u003e {\n        return new Promise\u003cT\u003e((resolve, reject): void =\u003e {\n            randomFill(array, (error: Error | null, array: T): void =\u003e {\n                if (error !== null) {\n                    reject(error);\n                    return;\n                }\n                resolve(array);\n            });\n        });\n    }\n}\n```\n\nAnd then (still in your Node.js application) use `RandomGenerator` as follows:\n\n```typescript\nimport { RandomGenerator } from '@diplomatiq/crypto-random';\nimport { NodeJsEntropyProvider } from './nodeJsEntropyProvider';\n\n// …\n\nasync function main() {\n    const entropyProvider = new NodeJsEntropyProvider();\n    const randomGenerator = new RandomGenerator(entropyProvider);\n    const randomString = await randomGenerator.alphanumeric(32);\n    // randomString will contain a 32-character-long alphanumeric string\n}\n```\n\n### Using a custom entropy source\n\n**WARNING!** Unless you are a seasoned cryptography expert possessing comprehensive knowledge about random/pseudo-random value generation, **DO NOT use any custom entropy source implementation other than the default**, or found in well-tested, popular _cryptographic_ libraries survived many years under public scrutiny. Cryptography — and mostly random generation — can be messed up very easily. If you use anything else than a CSPRNG/TRNG for gathering entropy, the values you generate using that entropy source will not be random in the cryptographic meaning, and thus will NOT be suitable for being used as passwords/keys/nonces/etc.\n\n## Discrete uniform distribution\n\nIn this library's context, discrete uniform distribution means that any character from a given alphabet will be chosen with equal probability into the generated random value. At generating any kind of cryptographic keys (passwords, authentication tokens, nonces), uniform distribution is crucial: in every other case the size of the key space decreases in some degree (thus finding the key is easier).\n\nThis library generates its random values following a discrete uniform distribution.\n\n## Development\n\nSee [CONTRIBUTING.md](https://github.com/Diplomatiq/crypto-random/blob/main/CONTRIBUTING.md) for details.\n\n---\n\nCopyright (c) 2018 Diplomatiq\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiplomatiq%2Fcrypto-random","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdiplomatiq%2Fcrypto-random","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiplomatiq%2Fcrypto-random/lists"}