Project: Random.Password.Generator



Generate a random password using Random class and LINQ:
void Main()
{
	const string seed = "";
	
	new Random(seed.GetHashCode())
		.Password(15)
		.Dump();
}

public static class RandomExtensions
{
	public static char NextChar(this Random random, char start, char stop)
	{
		return
			(char)random.Next((int)start, (int)stop);
	}
	
	public static char Char(this Random random, params char[] charGroup)
	{
		return
			charGroup[random.Next(0, charGroup.Length)];
	}
	
	public static string Password(this Random random, int length)
	{
		return Password(random, length, false, false, false);
	}
	
	public static string Password(this Random random, int length, bool numbers = true, bool lowercase = true, bool symbols = true)
	{
		var password = 
			Enumerable
				.Range(1, length)
				.Select(e => random.NextChar('A', 'Z'))
				.ToList();
		
		Enumerable
			.Range(1, length / 3)
			.Where(f => numbers)
			.ToList()			
			.ForEach(i => password[random.Next(1, length)] = random.NextChar('0', '9'));
	
		Enumerable
			.Range(1, length / 3)
			.Where(f => lowercase)

			.ToList()
			.ForEach(i => password[random.Next(1, length)] = random.NextChar('a', 'z'));
	
		Enumerable
			.Range(1, length / 8)
			.Where(f => symbols)
			.ToList()
			.ForEach(i => password[random.Next(1, length)] = random.Char(new[] { '.', ',', '!' }));
		
		return
			string.Join(null, password);
	}
}

Last edited Apr 23, 2012 at 4:49 PM by teoarch, version 2

Comments

No comments yet.