Skip to content

Instantly share code, notes, and snippets.

@theuntitled
Created April 15, 2016 08:50
Show Gist options
  • Save theuntitled/c5a1bb2a950bef86ef2895b005f95933 to your computer and use it in GitHub Desktop.
Save theuntitled/c5a1bb2a950bef86ef2895b005f95933 to your computer and use it in GitHub Desktop.
Mnemonic Password Generator
using System;
using System.Collections.Generic;
namespace Gists
{
public static class ListExtensions
{
public static T GetRandom<T>(this List<T> list, Random random = null)
{
random = random ?? new Random();
return list[random.Next(0, list.Count)];
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Gists
{
public class PasswordGenerator
{
public static string GenerateMnemonic(int passwordLength, int numberAmount, bool mixedCase, int? seed = null)
{
var password = new StringBuilder();
var vowels = new List<char> { 'a', 'e', 'i', 'o', 'e' };
var consonants = new List<char> { 'b', 'c', 'd', 'f', 'g', 'h', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z', 'y' };
if (mixedCase)
{
vowels.AddRange(vowels.Select(char.ToUpper).ToList());
consonants.AddRange(consonants.Select(char.ToUpper).ToList());
}
var random = new Random(seed ?? Environment.TickCount);
for (var i = 0; i < passwordLength/2; i++)
{
password.Append(vowels.GetRandom(random));
password.Append(consonants.GetRandom(random));
}
if (numberAmount == 0)
{
return password.ToString();
}
var numberPosition = random.Next(2, passwordLength - 2 - numberAmount);
return string.Concat(
password.ToString().Substring(0, numberPosition),
random.Next((int) Math.Pow(10, numberAmount - 1), (int) Math.Pow(10, numberAmount) - 1),
password.ToString().Substring(numberPosition + numberAmount)
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment