How do I generate a secure random string? #4701
-
I am trying to create a secure random string that I can hash and serialize to JSON. I was able to find import gleam/bit_array
import gleam/crypto.{Sha256}
pub fn main() -> Nil {
let secret = crypto.strong_random_bytes(24)
let secret_hash = crypto.hash(Sha256, secret)
let _ = echo bit_array.to_string(secret_hash)
Nil
} I get I found this in Javascript that seems to do what I would like: function generateSecureRandomString(): string {
// Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)
const alphabet = "abcdefghijklmnpqrstuvwxyz23456789";
// Generate 24 bytes = 192 bits of entropy.
// We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits
const bytes = new Uint8Array(24);
crypto.getRandomValues(bytes);
let id = "";
for (let i = 0; i < bytes.length; i++) {
// >> 3 s"removes" the right-most 3 bits of the byte
id += alphabet[bytes[i] >> 3];
}
return id;
} But I don't know how to convert the for-loop to Gleam. Is there a way of generating a secure random string in Gleam? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello! The way to go about it would be to base64 (or base16) encode the bit array, that will never fail to produce a valid UTF8 encoded string. For that you can use the |
Beta Was this translation helpful? Give feedback.
Hello! The way to go about it would be to base64 (or base16) encode the bit array, that will never fail to produce a valid UTF8 encoded string. For that you can use the
bit_array.base64_encode
function from stdlib