generate a secure random string in javascript

To generate a secure random string in JavaScript, we can use the crypto.getRandomValues() method, which generates a cryptographically random number. We can then convert the number to a string using the toString() method and encode it as base64 using the btoa() method. Here's an example function that generates a random string of a given length:

index.tsx
function generateRandomString(length) {
  var array = new Uint8Array(length);
  crypto.getRandomValues(array);
  var randomString = "";
  for (var i = 0; i < length; i++) {
    randomString += String.fromCharCode(array[i]);
  }
  return btoa(randomString);
}
259 chars
10 lines

This function creates a Uint8Array of length length, which is then filled with random values using crypto.getRandomValues(). The values are then converted to a string and encoded as base64. Finally, the function returns the resulting random string.

To use the function, simply call it with the desired length of the random string:

index.tsx
var randomString = generateRandomString(10);
console.log(randomString); // e.g. "Pj7+MznHwQ=="
95 chars
3 lines

gistlibby LogSnag