Skip to content
DeveloperMemos

How to Generate Cryptographically Unique Strings in Deno

Deno, Cryptography, Security, Random Strings1 min read

In security-sensitive applications, generating cryptographically strong random strings is crucial. Whether you're creating session tokens, unique identifiers, or secure keys, Deno provides tools to ensure randomness and uniqueness. In this article, we'll explore two approaches for generating cryptographically unique strings.

Approach 1: Using Crypto.getRandomValues

Deno's built-in Crypto.getRandomValues function allows us to obtain cryptographically strong random values. We'll create a function that generates a random hex string of a specified length:

1function getRandomString(length: number): string {
2 if (length % 2 !== 0) {
3 throw new Error("Only even sizes are supported");
4 }
5 const buffer = new Uint8Array(length / 2);
6 crypto.getRandomValues(buffer);
7 let result = "";
8 for (let i = 0; i < buffer.length; ++i) {
9 result += ("0" + buffer[i].toString(16)).slice(-2);
10 }
11 return result;
12}
13
14// Example usage and output(this will change on every execution):
15console.log(getRandomString(10)); // e2251fedb2
16console.log(getRandomString(50)); // da8ecbb859b8ba9b3ba60a201d666c75e68c32498d9afd7198
17console.log(getRandomString(100)); // ad68a5bf4497b5a6e7a53cce17cea8bb4e5829aab6f198c3d09e614ed3756df9440b391caa389b081809b2c000a95aac9ca4

Approach 2: Third-Party Modules

If you prefer a simpler solution, consider using third-party modules. Two popular options are:

  1. crypto_random_string: This module provides an easy API for generating cryptographically strong random strings. Install it using deno install --unstable -A -n crypto_random_string https://deno.land/x/crypto_random_string/mod.ts.

  2. nanoid: The nanoid library generates unique, URL-friendly string IDs. Install it with deno install --unstable -A -n nanoid https://deno.land/x/nanoid/mod.ts.

Wrapping Up

Choose the approach that best fits your project's requirements. Remember to prioritize security and uniqueness when handling sensitive data. Happy coding! 😊