create a password with a custom length and symbols in rust

To create a password with a custom length and symbols in Rust, you can use the rand crate to generate random characters and concatenate them to form the password.

Here's an example function that takes a password length and randomly generates a password based on the characters defined in an array:

main.rs
use rand::Rng;

fn generate_password(length: usize) -> String {
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                            abcdefghijklmnopqrstuvwxyz\
                            0123456789)(*&^%$#@!~";
    let charset_len = CHARSET.len();
    
    let mut rng = rand::thread_rng();
    let password: String = (0..length)
        .map(|_| {
            let idx = rng.gen_range(0, charset_len);
            char::from(CHARSET[idx])
        })
        .collect();
    
    password
}
508 chars
19 lines

In this function, the CHARSET constant defines the characters that can be used in the password. Here, we have included upper and lower case letters, numbers, and some symbols.

The function then uses the rand::thread_rng() function from the rand crate to initialize a random number generator. It then generates a random password by iterating length times, randomly selecting a character from the CHARSET array, and appending that character to the password.

You can call this function with a desired length to obtain a randomly generated password:

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

This will generate a password with 12 characters using the characters defined in CHARSET.

gistlibby LogSnag