public static ProtectedString Generate(PasswordGenerationOptions opt, bool bReturnProtected, byte[] pbAdditionalEntropy) { Debug.Assert(opt != null); if (opt == null) { throw new ArgumentNullException(); } if (opt.GeneratorType == PasswordGeneratorType.CustomCharSet) { return(CustomCharSetGenerate(opt.CustomCharSet, opt.PasswordLength, bReturnProtected, pbAdditionalEntropy)); } else if (opt.GeneratorType == PasswordGeneratorType.CharSpaces) { CustomCharSet ccs = CreateCustomCharSet(opt.CharSpaces); return(CustomCharSetGenerate(ccs, opt.PasswordLength, bReturnProtected, pbAdditionalEntropy)); } else if (opt.GeneratorType == PasswordGeneratorType.Pattern) { return(PatternGenerate(opt.Pattern, bReturnProtected, pbAdditionalEntropy)); } else { Debug.Assert(false); return(new ProtectedString(false, string.Empty)); } }
private static CustomCharSet CreateCustomCharSet(CharSpaces opt) { CustomCharSet ccs = new CustomCharSet(); if (opt.UpperCase) { ccs.Add(CharSetUpper); } if (opt.LowerCase) { ccs.Add(CharSetLower); } if (opt.Numeric) { ccs.Add(CharSetNumeric); } if (opt.Underline) { ccs.Add('_'); } if (opt.Minus) { ccs.Add('-'); } if (opt.Space) { ccs.Add(' '); } if (opt.Special) { ccs.Add(@"!#$%&'*+,./:;=?@^"); ccs.Add('\"'); ccs.Add('\\'); } if (opt.Brackets) { ccs.Add(@"()[]{}<>"); } if (opt.HighANSI) { for (char ch = '~'; ch < 255; ++ch) { ccs.Add(ch); } } return(ccs); }
private static ProtectedString CustomCharSetGenerate(CustomCharSet charSet, uint uPasswordLength, bool bReturnProtected, byte[] pbAdditionalEntropy) { Debug.Assert(charSet != null); if (charSet == null) { throw new ArgumentNullException(); } if (charSet.UCount == 0) { return(new ProtectedString(false, string.Empty)); } if (uPasswordLength == 0) { return(new ProtectedString(false, string.Empty)); } CryptoRandomStream crs = CreateCryptoStream(pbAdditionalEntropy); UTF8Encoding utf8 = new UTF8Encoding(); uint uGeneratedCount = 0, uNewCharIndex, uRandomPos = 0; byte[] pbRandom = crs.GetRandomBytes(1024); bool b16BitIndex = (charSet.UCount > 256); char[] vGenerated = new char[uPasswordLength]; Array.Clear(vGenerated, 0, vGenerated.Length); while (uGeneratedCount < uPasswordLength) { uNewCharIndex = pbRandom[uRandomPos]; ++uRandomPos; if (b16BitIndex) { uNewCharIndex *= 256; uNewCharIndex += pbRandom[uRandomPos]; ++uRandomPos; } if (uRandomPos >= (uint)pbRandom.Length) { pbRandom = CryptoRandom.GetRandomBytes(1024); uRandomPos = 0; } if (uNewCharIndex < charSet.UCount) { vGenerated[uGeneratedCount] = charSet[uNewCharIndex]; ++uGeneratedCount; } } if (Array.IndexOf <char>(vGenerated, char.MinValue) >= 0) { Debug.Assert(false); throw new System.Security.SecurityException(); } byte[] pbUTF8 = utf8.GetBytes(vGenerated); ProtectedString ps = new ProtectedString(bReturnProtected, pbUTF8); Array.Clear(pbUTF8, 0, pbUTF8.Length); Array.Clear(vGenerated, 0, vGenerated.Length); return(ps); }