コード例 #1
0
        private IEnumerable <string> SelectPhrases(IRandomNumberGenerator random, int wordCount, int phraseCount, bool spaces, int minChars, int maxChars, NumericStyles whenNumeric, int numbersToAdd, AllUppercaseStyles whenUpper, int uppersToAdd)
        {
            if (minChars > maxChars)
            {
                yield break;
            }

            phraseCount = Math.Min(phraseCount, MaxCount);
            wordCount   = Math.Min(wordCount, MaxWords);
            if (phraseCount <= 0 || wordCount <= 0)
            {
                yield break;
            }

            var sw       = System.Diagnostics.Stopwatch.StartNew();
            var sb       = new StringBuilder();
            var dict     = Dictionary.Value;
            int attempts = 0;

            ICollection <IMutator> mutators = null;

            if (whenNumeric != NumericStyles.Never || whenUpper != AllUppercaseStyles.Never)
            {
                mutators = new List <IMutator>();
            }
            if (whenNumeric != NumericStyles.Never)
            {
                mutators.Add(new NumericMutator()
                {
                    When = whenNumeric, NumberOfNumbersToAdd = numbersToAdd
                });
            }
            if (whenUpper == AllUppercaseStyles.Anywhere)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.Anywhere, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.StartOfWord)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.StartOfWord, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.WholeWord)
            {
                mutators.Add(new UppercaseWordMutator()
                {
                    NumberOfWordsToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.RunOfLetters)
            {
                mutators.Add(new UppercaseRunMutator()
                {
                    NumberOfRuns = uppersToAdd
                });
            }
            MurrayGrant.ReadablePassphrase.Random.RandomSourceBase randomWrapper = null;
            if (mutators != null)
            {
                randomWrapper = new MurrayGrant.ReadablePassphrase.Random.ExternalRandomSource(random.GetRandomBytes);
            }

            for (int c = 0; c < phraseCount; c++)
            {
                do
                {
                    // Generate a phrase.
                    for (int l = 0; l < wordCount; l++)
                    {
                        sb.Append(dict[random.GetRandomInt32(dict.Count)]);
                        sb.Append(' ');
                    }
                    sb.Remove(sb.Length - 1, 1);

                    // Apply mutators.
                    if (mutators != null)
                    {
                        foreach (var m in mutators)
                        {
                            m.Mutate(sb, randomWrapper);
                        }
                    }

                    // Finally, remove spaces if required (as the mutators depend on whitespace to do their work).
                    if (!spaces)
                    {
                        for (int i = sb.Length - 1; i >= 0; i--)
                        {
                            if (sb[i] == ' ')
                            {
                                sb.Remove(i, 1);
                            }
                        }
                    }

                    attempts++;

                    // Ensure the final phrase is within the min / max chars.
                } while (attempts < MaxAttemptsPerCount && (sb.Length < minChars || sb.Length > maxChars));
                if (attempts >= MaxAttemptsPerCount)
                {
                    sb.Clear();
                    sb.Append("A passphrase could not be found matching your minimum and maximum length requirements");
                }


                // Yield the phrase and reset state.
                var result = sb.ToString();
                yield return(result);

                sb.Clear();
                attempts = 0;
            }
            sw.Stop();

            var bytesRequested = (int)((random as Terninger.Random.CypherBasedPrngGenerator)?.BytesRequested).GetValueOrDefault();

            RandomService.LogPasswordStat("Passphrase", phraseCount, sw.Elapsed, bytesRequested, IPAddressHelpers.GetHostOrCacheIp(Request).AddressFamily, HttpContext.GetApiKeyId());
            if (!IpThrottlerService.HasAnyUsage(IPAddressHelpers.GetHostOrCacheIp(this.HttpContext.Request)))
            {
                RandomService.AddWebRequestEntropy(this.Request);
            }
            IpThrottlerService.IncrementUsage(IPAddressHelpers.GetHostOrCacheIp(this.HttpContext.Request), phraseCount);
        }
コード例 #2
0
        private IEnumerable <string> SelectPhrases(WordDictionary dictionary, IRandomNumberGenerator random, PhraseStrength strength, int phraseCount, bool includeSpaces, int minChars, int maxChars, NumericStyles whenNumeric, int numbersToAdd, AllUppercaseStyles whenUpper, int uppersToAdd)
        {
            if (minChars > maxChars)
            {
                yield break;
            }

            phraseCount = Math.Min(phraseCount, MaxCount);
            if (phraseCount <= 0)
            {
                yield break;
            }

            var sw        = System.Diagnostics.Stopwatch.StartNew();
            var generator = this.GetGenerator(dictionary, random);
            int attempts  = 0;

            // Setup mutators.
            ICollection <IMutator> mutators = null;

            if (whenNumeric != NumericStyles.Never || whenUpper != AllUppercaseStyles.Never)
            {
                mutators = new List <IMutator>();
            }
            if (whenNumeric != NumericStyles.Never)
            {
                mutators.Add(new NumericMutator()
                {
                    When = whenNumeric, NumberOfNumbersToAdd = numbersToAdd
                });
            }
            if (whenUpper == AllUppercaseStyles.Anywhere)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.Anywhere, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.StartOfWord)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.StartOfWord, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.WholeWord)
            {
                mutators.Add(new UppercaseWordMutator()
                {
                    NumberOfWordsToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.RunOfLetters)
            {
                mutators.Add(new UppercaseRunMutator()
                {
                    NumberOfRuns = uppersToAdd
                });
            }

            for (int c = 0; c < phraseCount; c++)
            {
                string candidate = "";
                do
                {
                    // Generate a phrase.
                    candidate = generator.Generate(strength, " ", mutators);

                    // Finally, remove spaces if required (as the mutators depend on whitespace to do their work).
                    if (!includeSpaces)
                    {
                        candidate = new string(candidate.Where(ch => ch != ' ').ToArray());
                    }
                    attempts++;

                    // Ensure the final phrase is within the min / max chars.
                } while (attempts < MaxAttemptsPerCount && (candidate.Length < minChars || candidate.Length > maxChars));
                if (attempts >= MaxAttemptsPerCount)
                {
                    candidate = "A passphrase could not be found matching your minimum and maximum length requirements";
                }

                // Yield the phrase and reset state.
                yield return(candidate);

                attempts = 0;
            }
            sw.Stop();

            PostSelectionAction("ReadablePassphrase", phraseCount, sw.Elapsed, random);
        }
コード例 #3
0
        static bool ParseCommandLine(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                var arg = args[i].ToLower().Trim();
                if (arg.StartsWith("-") || arg.StartsWith("--") || arg.StartsWith("/"))
                {
                    arg = arg.Replace("--", "").Replace("-", "").Replace("/", "");
                }

                if (arg == "c" || arg == "count")
                {
                    if (!Int32.TryParse(args[i + 1].Trim(), out count))
                    {
                        Console.WriteLine("Unable to parse number '{0}' for 'count' option.", args[i + 1]);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "s" || arg == "strength")
                {
                    if (!Enum.GetNames(typeof(PhraseStrength)).Select(x => x.ToLower()).Contains(args[i + 1]))
                    {
                        Console.WriteLine("Unknown 'strength' option '{0}'.", args[i + 1]);
                        return(false);
                    }
                    strength = (PhraseStrength)Enum.Parse(typeof(PhraseStrength), args[i + 1], true);
                    i++;
                }
                else if (arg == "spaces")
                {
                    bool includeSpaces;
                    if (!Boolean.TryParse(args[i + 1], out includeSpaces))
                    {
                        Console.WriteLine("Invalid boolean '{0}' for 'spaces' option.", args[i + 1]);
                        return(false);
                    }
                    else if (includeSpaces)
                    {
                        wordSeparator = " ";
                    }
                    else if (!includeSpaces)
                    {
                        wordSeparator = "";
                    }
                    i++;
                }
                else if (arg == "separator")
                {
                    wordSeparator = args[i + 1];
                    i++;
                }
                else if (arg == "d" || arg == "dict")
                {
                    var customDictionaryPath = args[i + 1];
                    loaderArguments = "file=" + customDictionaryPath;
                    if (!System.IO.File.Exists(customDictionaryPath))
                    {
                        Console.WriteLine("Unable to find file '{0}' for 'dict' option.", customDictionaryPath);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "l" || arg == "loaderdll")
                {
                    loaderDll = args[i + 1];
                    if (!System.IO.File.Exists(loaderDll))
                    {
                        Console.WriteLine("Unable to find file '{0}' for 'loaderdll' option.", loaderDll);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "t" || arg == "loadertype")
                {
                    loaderType = args[i + 1];
                    i++;
                }
                else if (arg == "a" || arg == "loaderargs")
                {
                    loaderArguments = args[i + 1];
                    i++;
                }
                else if (arg == "n" || arg == "nongrammar")
                {
                    if (!Int32.TryParse(args[i + 1].Trim(), out anyLength))
                    {
                        Console.WriteLine("Unable to parse number '{0}' for 'nongrammar' option.", args[i + 1]);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "p" || arg == "phrase")
                {
                    customPhrasePath = args[i + 1];
                    if (!System.IO.File.Exists(customPhrasePath))
                    {
                        Console.WriteLine("Unable to find file '{0}' for 'phrase' option.", args[i + 1]);
                        return(false);
                    }
                    try
                    {
                        phraseDescription = ReadablePassphrase.PhraseDescription.Clause.CreateCollectionFromTextString(System.IO.File.ReadAllText(customPhrasePath));
                    }
                    catch (PhraseDescriptionParseException ex)
                    {
                        Console.WriteLine("Unable to parse file '{0}' for 'phrase' option:", args[i + 1]);
                        Console.WriteLine("  {0}", ex.Message);
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine("  {0}: {1}", ex.InnerException.GetType().Name, ex.InnerException.Message);
                        }
                    }
                    i++;
                }
                else if (arg == "min")
                {
                    if (!Int32.TryParse(args[i + 1].Trim(), out minLength))
                    {
                        Console.WriteLine("Unable to parse number '{0}' for 'min' option.", args[i + 1]);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "max")
                {
                    if (!Int32.TryParse(args[i + 1].Trim(), out maxLength))
                    {
                        Console.WriteLine("Unable to parse number '{0}' for 'max' option.", args[i + 1]);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "m" || arg == "stdMutators")
                {
                    applyStandardMutators = true;
                }
                else if (arg == "m2" || arg == "altMutators")
                {
                    applyAlternativeMutators = true;
                }
                else if (arg == "mutnumeric")
                {
                    if (!Enum.GetNames(typeof(NumericStyles)).Select(x => x.ToLower()).Contains(args[i + 1]))
                    {
                        Console.WriteLine("Unknown 'mutNumeric' option '{0}'.", args[i + 1]);
                        return(false);
                    }
                    numericStyle = (NumericStyles)Enum.Parse(typeof(NumericStyles), args[i + 1], true);
                    i++;
                }
                else if (arg == "mutnumericcount")
                {
                    if (!Int32.TryParse(args[i + 1].Trim(), out numericCount))
                    {
                        Console.WriteLine("Unable to parse number '{0}' for 'mutNumericCount' option.", args[i + 1]);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "mutupper")
                {
                    if (!Enum.GetNames(typeof(AllUppercaseStyles)).Select(x => x.ToLower()).Contains(args[i + 1]))
                    {
                        Console.WriteLine("Unknown 'mutUpper' option '{0}'.", args[i + 1]);
                        return(false);
                    }
                    upperStyle = (AllUppercaseStyles)Enum.Parse(typeof(AllUppercaseStyles), args[i + 1], true);
                    i++;
                }
                else if (arg == "mutuppercount")
                {
                    if (!Int32.TryParse(args[i + 1].Trim(), out upperCount))
                    {
                        Console.WriteLine("Unable to parse number '{0}' for 'mutUpperCount' option.", args[i + 1]);
                        return(false);
                    }
                    i++;
                }
                else if (arg == "mutconstant")
                {
                    if (!Enum.GetNames(typeof(ConstantStyles)).Select(x => x.ToLower()).Contains(args[i + 1]))
                    {
                        Console.WriteLine("Unknown 'mutConstant' option '{0}'.", args[i + 1]);
                        return(false);
                    }
                    constantStyle = (ConstantStyles)Enum.Parse(typeof(ConstantStyles), args[i + 1], true);
                    i++;
                }
                else if (arg == "mutconstantvalue")
                {
                    constantValue = args[i + 1];
                    i++;
                }
                else if (arg == "q" || arg == "quiet")
                {
                    quiet = true;
                }
                else if (arg == "h" || arg == "help")
                {
                    PrintUsage();
                    Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("Unknown argument '{0}'.", arg);
                    return(false);
                }
            }

            return(true);
        }
コード例 #4
0
        private IEnumerable <string> SelectPhrases(IRandomNumberGenerator random, PhraseStrength strength, int phraseCount, bool includeSpaces, int minChars, int maxChars, NumericStyles whenNumeric, int numbersToAdd, AllUppercaseStyles whenUpper, int uppersToAdd)
        {
            if (minChars > maxChars)
            {
                yield break;
            }

            phraseCount = Math.Min(phraseCount, MaxCount);
            if (phraseCount <= 0)
            {
                yield break;
            }

            var sw        = System.Diagnostics.Stopwatch.StartNew();
            var generator = this.GetGenerator(random);
            int attempts  = 0;
            ICollection <IMutator> mutators = null;

            if (whenNumeric != NumericStyles.Never || whenUpper != AllUppercaseStyles.Never)
            {
                mutators = new List <IMutator>();
            }
            if (whenNumeric != NumericStyles.Never)
            {
                mutators.Add(new NumericMutator()
                {
                    When = whenNumeric, NumberOfNumbersToAdd = numbersToAdd
                });
            }
            if (whenUpper == AllUppercaseStyles.Anywhere)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.Anywhere, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.StartOfWord)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.StartOfWord, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.WholeWord)
            {
                mutators.Add(new UppercaseWordMutator()
                {
                    NumberOfWordsToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.RunOfLetters)
            {
                mutators.Add(new UppercaseRunMutator()
                {
                    NumberOfRuns = uppersToAdd
                });
            }

            for (int c = 0; c < phraseCount; c++)
            {
                string candidate = "";
                do
                {
                    // Generate a phrase.
                    candidate = generator.Generate(strength, " ", mutators);

                    // Finally, remove spaces if required (as the mutators depend on whitespace to do their work).
                    if (!includeSpaces)
                    {
                        candidate = new string(candidate.Where(ch => ch != ' ').ToArray());
                    }
                    attempts++;

                    // Ensure the final phrase is within the min / max chars.
                } while (attempts < MaxAttemptsPerCount && (candidate.Length < minChars || candidate.Length > maxChars));
                if (attempts >= MaxAttemptsPerCount)
                {
                    candidate = "A passphrase could not be found matching your minimum and maximum length requirements";
                }

                // Yield the phrase and reset state.
                yield return(candidate);

                attempts = 0;
            }
            sw.Stop();

            var bytesRequested = (int)((random as Terninger.Random.CypherBasedPrngGenerator)?.BytesRequested).GetValueOrDefault();

            RandomService.LogPasswordStat("ReadablePassphrase", phraseCount, sw.Elapsed, bytesRequested, IPAddressHelpers.GetHostOrCacheIp(Request).AddressFamily, HttpContext.GetApiKeyId());
            if (!IpThrottlerService.HasAnyUsage(IPAddressHelpers.GetHostOrCacheIp(this.HttpContext.Request)))
            {
                RandomService.AddWebRequestEntropy(this.Request);
            }
            IpThrottlerService.IncrementUsage(IPAddressHelpers.GetHostOrCacheIp(this.HttpContext.Request), phraseCount);
        }
コード例 #5
0
        private IEnumerable <string> SelectPhrases(IList <string> dict, IRandomNumberGenerator random, int wordCount, int phraseCount, bool spaces, int minChars, int maxChars, NumericStyles whenNumeric, int numbersToAdd, AllUppercaseStyles whenUpper, int uppersToAdd)
        {
            if (minChars > maxChars)
            {
                yield break;
            }

            phraseCount = Math.Min(phraseCount, MaxCount);
            wordCount   = Math.Min(wordCount, MaxWords);
            if (phraseCount <= 0 || wordCount <= 0)
            {
                yield break;
            }

            var sw       = System.Diagnostics.Stopwatch.StartNew();
            var sb       = new StringBuilder();
            int attempts = 0;

            // Setup any mutators required.
            ICollection <IMutator> mutators = null;

            if (whenNumeric != NumericStyles.Never || whenUpper != AllUppercaseStyles.Never)
            {
                mutators = new List <IMutator>();
            }
            if (whenNumeric != NumericStyles.Never)
            {
                mutators.Add(new NumericMutator()
                {
                    When = whenNumeric, NumberOfNumbersToAdd = numbersToAdd
                });
            }
            if (whenUpper == AllUppercaseStyles.Anywhere)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.Anywhere, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.StartOfWord)
            {
                mutators.Add(new UppercaseMutator()
                {
                    When = UppercaseStyles.StartOfWord, NumberOfCharactersToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.WholeWord)
            {
                mutators.Add(new UppercaseWordMutator()
                {
                    NumberOfWordsToCapitalise = uppersToAdd
                });
            }
            else if (whenUpper == AllUppercaseStyles.RunOfLetters)
            {
                mutators.Add(new UppercaseRunMutator()
                {
                    NumberOfRuns = uppersToAdd
                });
            }
            MurrayGrant.ReadablePassphrase.Random.RandomSourceBase randomWrapper = null;
            if (mutators != null)
            {
                randomWrapper = new MurrayGrant.ReadablePassphrase.Random.ExternalRandomSource(random.GetRandomBytes);
            }

            for (int c = 0; c < phraseCount; c++)
            {
                do
                {
                    // Generate a phrase.
                    for (int l = 0; l < wordCount; l++)
                    {
                        sb.Append(dict[random.GetRandomInt32(dict.Count)]);
                        sb.Append(' ');
                    }
                    sb.Remove(sb.Length - 1, 1);

                    // Apply mutators.
                    if (mutators != null)
                    {
                        foreach (var m in mutators)
                        {
                            m.Mutate(sb, randomWrapper);
                        }
                    }

                    // Finally, remove spaces if required (as the mutators depend on whitespace to do their work).
                    if (!spaces)
                    {
                        for (int i = sb.Length - 1; i >= 0; i--)
                        {
                            if (sb[i] == ' ')
                            {
                                sb.Remove(i, 1);
                            }
                        }
                    }

                    attempts++;

                    // Ensure the final phrase is within the min / max chars.
                } while (attempts < MaxAttemptsPerCount && (sb.Length < minChars || sb.Length > maxChars));
                if (attempts >= MaxAttemptsPerCount)
                {
                    sb.Clear();
                    sb.Append("A passphrase could not be found matching your minimum and maximum length requirements");
                }


                // Yield the phrase and reset state.
                var result = sb.ToString();
                yield return(result);

                sb.Clear();
                attempts = 0;
            }
            sw.Stop();

            PostSelectionAction("Passphrase", phraseCount, sw.Elapsed, random);
        }