create a password with a custom length in rust

To generate a password with a custom length in Rust, you can use the rand crate to generate random characters.

First, add the following line to your Cargo.toml file:

[dependencies]
rand = "0.8.4"
30 chars
3 lines

Then, in your Rust code, you can generate a random password with custom length as follows:

main.rs
use rand::Rng;

fn generate_password(length: usize) -> String {
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                            abcdefghijklmnopqrstuvwxyz\
                            0123456789)(*&^%$#@!~";
    let mut rng = rand::thread_rng();

    let password: String = (0..length)
        .map(|_| {
            let index = rng.gen_range(0..CHARSET.len());
            CHARSET[index] as char
        })
        .collect();

    password
}
465 chars
18 lines

This function takes a length parameter that specifies the length of the password to generate. It creates a CHARSET constant that contains all the possible characters that could be used in the password.

It then creates a String of random characters with the given length by iterating over each character and selecting a random character from the CHARSET constant. Finally, it collects the random characters into a String and returns it.

Example usage:

main.rs
fn main() {
    let password = generate_password(12);
    println!("Generated password: {}", password);
}
106 chars
5 lines

gistlibby LogSnag