Rust Password Generator
A very small Rust project that generates simple random passwords.
It's a basic program, but making utilities like this is a rite of passage when learning a new language. So really, this was built to give me a bit of practice with Rust.
The code is included at the bottom of this post.
Usage
Help Info
When called with no arguments, the tool presents help information:
$ passgen
passgen (v0.1.0) Password generator
Usage: passgen <length> <count>
Generating A 16 Character Password
$ passgen 16
qsCbV5znL981zSlW
Generating Several Passwords
$ passgen 16 8
cBOPbcPclBtdyO3F
6UGOoN7qMojrw6Tg
86itbhsuSVtGeLu7
BZCBFK4qma0XR0gA
VFuaElVxveOMhm4I
kxi9Dfq1AhKtn3T5
KYMX5u1JTKvgq0BI
MNGEOUbzuoYq0aFz
The Code
main.rs
:
extern crate rand;
use rand::thread_rng;
use rand::Rng;
use rand::distributions::Alphanumeric;
fn generate_passwords(length: &str, count: &str) {
let length = length.parse::<usize>().expect("[ ERROR ] Invalid password length");
let count = count.parse::<u8>().expect("[ ERROR ] Invalid number of passwords");
for _ in 0..count {
generate_password(length);
}
}
fn generate_password(length: usize) {
let rng = thread_rng();
let password: String = rng.sample_iter(&Alphanumeric).take(length).collect();
println!("{}", password);
}
fn title() -> String {
let mut title = String::from(env!("CARGO_PKG_NAME"));
title.push_str(&format!(" (v{}) ", env!("CARGO_PKG_VERSION")).to_string());
title.push_str(env!("CARGO_PKG_DESCRIPTION"));
title
}
fn usage() {
println!("{}", title());
println!("Usage: {} <length> <count>", env!("CARGO_PKG_NAME"));
}
fn main() {
let args: Vec<String> = std::env::args().collect();
match args.len() {
3 => generate_passwords(&args[1], &args[2]),
2 => generate_passwords(&args[1], "1"),
_ => usage()
}
}
Cargo.toml
:
[package]
name = "passgen"
version = "0.1.0"
edition = "2021"
description = "Password generator"
[dependencies]
rand = "0.7.3"
Published: December 18, 2021
Categories:
infrastructure