public static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, byte[] pbUserEntropy, CustomPwGeneratorPool pwAlgorithmPool) { Debug.Assert(pwProfile != null); if(pwProfile == null) throw new ArgumentNullException("pwProfile"); PwgError e = PwgError.Unknown; CryptoRandomStream crs = null; byte[] pbKey = null; try { crs = CreateRandomStream(pbUserEntropy, out pbKey); if(pwProfile.GeneratorType == PasswordGeneratorType.CharSet) e = CharSetBasedGenerator.Generate(out psOut, pwProfile, crs); else if(pwProfile.GeneratorType == PasswordGeneratorType.Pattern) e = PatternBasedGenerator.Generate(out psOut, pwProfile, crs); else if(pwProfile.GeneratorType == PasswordGeneratorType.Custom) e = GenerateCustom(out psOut, pwProfile, crs, pwAlgorithmPool); else { Debug.Assert(false); psOut = ProtectedString.Empty; } } finally { if(crs != null) crs.Dispose(); if(pbKey != null) MemUtil.ZeroByteArray(pbKey); } return e; }
public static PwgError Generate(ProtectedString psOutBuffer, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { if(pwProfile.Length == 0) return PwgError.Success; PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString()); char[] vGenerated = new char[pwProfile.Length]; PwGenerator.PrepareCharSet(pcs, pwProfile); for(int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex) { char ch = PwGenerator.GenerateCharacter(pwProfile, pcs, crsRandomSource); if(ch == char.MinValue) { Array.Clear(vGenerated, 0, vGenerated.Length); return PwgError.TooFewCharacters; } vGenerated[nIndex] = ch; } byte[] pbUTF8 = Encoding.UTF8.GetBytes(vGenerated); psOutBuffer.SetString(Encoding.UTF8.GetString(pbUTF8, 0, pbUTF8.Length)); Array.Clear(pbUTF8, 0, pbUTF8.Length); Array.Clear(vGenerated, 0, vGenerated.Length); return PwgError.Success; }
internal static bool PrepareCharSet(PwCharSet pwCharSet, PwProfile pwProfile) { uint cc = pwCharSet.Size; for (uint i = 0; i < cc; ++i) { char ch = pwCharSet[i]; if ((ch == char.MinValue) || (ch == '\t') || (ch == '\r') || (ch == '\n') || char.IsSurrogate(ch)) { return(false); } } if (pwProfile.ExcludeLookAlike) { pwCharSet.Remove(PwCharSet.LookAlike); } if (!string.IsNullOrEmpty(pwProfile.ExcludeCharacters)) { pwCharSet.Remove(pwProfile.ExcludeCharacters); } return(true); }
public static PwgError Generate(ProtectedString psOutBuffer, PwProfile pwProfile, byte[] pbUserEntropy) { Debug.Assert(psOutBuffer != null); if (psOutBuffer == null) { throw new ArgumentNullException("psOutBuffer"); } Debug.Assert(pwProfile != null); if (pwProfile == null) { throw new ArgumentNullException("pwProfile"); } psOutBuffer.Clear(); CryptoRandomStream crs = CreateCryptoStream(pbUserEntropy); PwgError e = PwgError.Unknown; if (pwProfile.GeneratorType == PasswordGeneratorType.CharSet) { e = CharSetBasedGenerator.Generate(psOutBuffer, pwProfile, crs); } else if (pwProfile.GeneratorType == PasswordGeneratorType.Pattern) { e = PatternBasedGenerator.Generate(psOutBuffer, pwProfile, crs); } else { Debug.Assert(false); } return(e); }
public static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, byte[] pbUserEntropy, CustomPwGeneratorPool pwAlgorithmPool) { Debug.Assert(pwProfile != null); if (pwProfile == null) { throw new ArgumentNullException("pwProfile"); } CryptoRandomStream crs = CreateCryptoStream(pbUserEntropy); PwgError e = PwgError.Unknown; if (pwProfile.GeneratorType == PasswordGeneratorType.CharSet) { e = CharSetBasedGenerator.Generate(out psOut, pwProfile, crs); } else if (pwProfile.GeneratorType == PasswordGeneratorType.Pattern) { e = PatternBasedGenerator.Generate(out psOut, pwProfile, crs); } else if (pwProfile.GeneratorType == PasswordGeneratorType.Custom) { e = GenerateCustom(out psOut, pwProfile, crs, pwAlgorithmPool); } else { Debug.Assert(false); psOut = ProtectedString.Empty; } return(e); }
public static PwgError Generate(ProtectedString psOutBuffer, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { if (pwProfile.Length == 0) { return(PwgError.Success); } PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString()); char[] vGenerated = new char[pwProfile.Length]; PwGenerator.PrepareCharSet(pcs, pwProfile); for (int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex) { char ch = PwGenerator.GenerateCharacter(pwProfile, pcs, crsRandomSource); if (ch == char.MinValue) { Array.Clear(vGenerated, 0, vGenerated.Length); return(PwgError.TooFewCharacters); } vGenerated[nIndex] = ch; } byte[] pbUTF8 = Encoding.UTF8.GetBytes(vGenerated); psOutBuffer.SetString(Encoding.UTF8.GetString(pbUTF8, 0, pbUTF8.Length)); Array.Clear(pbUTF8, 0, pbUTF8.Length); Array.Clear(vGenerated, 0, vGenerated.Length); return(PwgError.Success); }
internal static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { psOut = ProtectedString.Empty; if(pwProfile.Length == 0) return PwgError.Success; PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString()); char[] vGenerated = new char[pwProfile.Length]; PwGenerator.PrepareCharSet(pcs, pwProfile); for(int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex) { char ch = PwGenerator.GenerateCharacter(pwProfile, pcs, crsRandomSource); if(ch == char.MinValue) { Array.Clear(vGenerated, 0, vGenerated.Length); return PwgError.TooFewCharacters; } vGenerated[nIndex] = ch; } byte[] pbUtf8 = StrUtil.Utf8.GetBytes(vGenerated); psOut = new ProtectedString(true, pbUtf8); MemUtil.ZeroByteArray(pbUtf8); Array.Clear(vGenerated, 0, vGenerated.Length); return PwgError.Success; }
public static int CompareProfilesByName(PwProfile a, PwProfile b) { if(a == b) return 0; if(a == null) { Debug.Assert(false); return -1; } if(b == null) { Debug.Assert(false); return 1; } return StrUtil.CompareNaturally(a.Name, b.Name); }
public static byte[] CollectEntropyIfEnabled(PwProfile pp) { if(pp.CollectUserEntropy == false) return null; EntropyForm ef = new EntropyForm(); if(ef.ShowDialog() == DialogResult.OK) return ef.GeneratedEntropy; return null; }
/// <summary> /// Initialize this password generator form instance. /// </summary> /// <param name="pwInitial">Initial options (may be <c>null</c>).</param> public void InitEx(PwProfile pwInitial, bool bCanAccept, bool bForceInTaskbar) { m_optInitial = pwInitial; m_bCanAccept = bCanAccept; // m_bForceInTaskbar = bForceInTaskbar; // Set ShowInTaskbar immediately, not later, otherwise the form // can disappear: // https://sourceforge.net/p/keepass/discussion/329220/thread/c95b5644/ if(bForceInTaskbar) this.ShowInTaskbar = true; }
private static void AddStdPattern(string strName, string strPattern) { PwProfile p = new PwProfile(); p.Name = strName; p.CollectUserEntropy = false; p.GeneratorType = PasswordGeneratorType.Pattern; p.Pattern = strPattern; Program.Config.PasswordGenerator.UserProfiles.Add(p); }
private static void AddStdPattern(string strName, string strPattern) { PwProfile p = new PwProfile(); p.Name = strName + PwGeneratorUtil.BuiltInSuffix; p.CollectUserEntropy = false; p.GeneratorType = PasswordGeneratorType.Pattern; p.Pattern = strPattern; m_lBuiltIn.Add(p); }
public static byte[] CollectEntropyIfEnabled(PwProfile pp) { if(!pp.CollectUserEntropy) return null; EntropyForm ef = new EntropyForm(); if(UIUtil.ShowDialogNotValue(ef, DialogResult.OK)) return null; byte[] pbGen = ef.GeneratedEntropy; UIUtil.DestroyForm(ef); return pbGen; }
public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource) { if (prf == null) { Debug.Assert(false); } else { Debug.Assert(prf.CustomAlgorithmUuid == Convert.ToBase64String( m_uuid.UuidBytes, Base64FormattingOptions.None)); } Random keylen = new Random((int)crsRandomSource.GetRandomUInt64()); int k = keylen.Next(3, 7); return new ProtectedString(false, cockPwdGenerator(k,keylen)); }
public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource) { if (prf == null) Debug.Assert(false); else Debug.Assert(prf.CustomAlgorithmUuid == Convert.ToBase64String(m_uuid.UuidBytes, Base64FormattingOptions.None)); if (string.IsNullOrEmpty(settings.WordListLocation)) { System.Windows.Forms.MessageBox.Show("No word list location"); GetSettingsFromUser(); return null; } if (!System.IO.File.Exists(settings.WordListLocation)) { System.Windows.Forms.MessageBox.Show(string.Format("Word List doesn't exist at location {0}", settings.WordListLocation)); GetSettingsFromUser(); return null; } try { if (words == null) words = System.IO.File.ReadAllLines(settings.WordListLocation); StringBuilder sb = new StringBuilder(); for (int i = 0; i < settings.NumberOfWords; i++) { ulong u = crsRandomSource.GetRandomUInt64(); u %= (ulong)(words.Length - 1); if (i > 0) sb.Append(settings.Separator); string word = words[u]; if (i == 0 && word.Length > 1) word = word.Substring(0, 1).ToUpper() + word.Substring(1, word.Length - 1); sb.Append(word); } sb.Append(settings.TrailingTrash); return new ProtectedString(false, sb.ToString()); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(string.Format("Encountered this error while generating password: {0}", ex.Message)); } return null; }
internal static void PrepareCharSet(PwCharSet pwCharSet, PwProfile pwProfile) { pwCharSet.Remove(PwCharSet.Invalid); if (pwProfile.ExcludeLookAlike) { pwCharSet.Remove(PwCharSet.LookAlike); } if (pwProfile.ExcludeCharacters.Length > 0) { pwCharSet.Remove(pwProfile.ExcludeCharacters); } }
public static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, byte[] pbUserEntropy, CustomPwGeneratorPool pwAlgorithmPool) { Debug.Assert(pwProfile != null); if (pwProfile == null) { throw new ArgumentNullException("pwProfile"); } PwgError e = PwgError.Unknown; CryptoRandomStream crs = null; byte[] pbKey = null; try { crs = CreateRandomStream(pbUserEntropy, out pbKey); if (pwProfile.GeneratorType == PasswordGeneratorType.CharSet) { e = CharSetBasedGenerator.Generate(out psOut, pwProfile, crs); } else if (pwProfile.GeneratorType == PasswordGeneratorType.Pattern) { e = PatternBasedGenerator.Generate(out psOut, pwProfile, crs); } else if (pwProfile.GeneratorType == PasswordGeneratorType.Custom) { e = GenerateCustom(out psOut, pwProfile, crs, pwAlgorithmPool); } else { Debug.Assert(false); psOut = ProtectedString.Empty; } } finally { if (crs != null) { crs.Dispose(); } if (pbKey != null) { MemUtil.ZeroByteArray(pbKey); } } return(e); }
internal static char GenerateCharacter(PwProfile pwProfile, PwCharSet pwCharSet, CryptoRandomStream crsRandomSource) { if(pwCharSet.Size == 0) return char.MinValue; ulong uIndex = crsRandomSource.GetRandomUInt64(); uIndex %= (ulong)pwCharSet.Size; char ch = pwCharSet[(uint)uIndex]; if(pwProfile.NoRepeatingCharacters) pwCharSet.Remove(ch); return ch; }
public void ExpandPattern() { // arrange var psOutBuffer = new ProtectedString(); var pwProfile = new PwProfile(); pwProfile.Pattern = "g{5}"; var pbKey = new byte[] { 0x00 }; var crsRandomSource = new CryptoRandomStream(CrsAlgorithm.Salsa20, pbKey); var error = PatternBasedGenerator.Generate(psOutBuffer, pwProfile, crsRandomSource); // act // nothing to do as ExpandPattern() would have been called by calling Generate() // assert Assert.AreEqual(PwgError.Success, error); var actual = psOutBuffer.ReadString(); Assert.AreEqual("ggggg", actual); }
internal static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { psOut = ProtectedString.Empty; if (pwProfile.Length == 0) { return(PwgError.Success); } PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString()); if (!PwGenerator.PrepareCharSet(pcs, pwProfile)) { return(PwgError.InvalidCharSet); } char[] v = new char[pwProfile.Length]; try { for (int i = 0; i < v.Length; ++i) { char ch = PwGenerator.GenerateCharacter(pcs, crsRandomSource); if (ch == char.MinValue) { return(PwgError.TooFewCharacters); } v[i] = ch; if (pwProfile.NoRepeatingCharacters) { pcs.Remove(ch); } } byte[] pbUtf8 = StrUtil.Utf8.GetBytes(v); psOut = new ProtectedString(true, pbUtf8); MemUtil.ZeroByteArray(pbUtf8); } finally { MemUtil.ZeroArray <char>(v); } return(PwgError.Success); }
internal static char GenerateCharacter(PwProfile pwProfile, PwCharSet pwCharSet, CryptoRandomStream crsRandomSource) { if (pwCharSet.Size == 0) { return(char.MinValue); } ulong uIndex = crsRandomSource.GetRandomUInt64(); uIndex %= (ulong)pwCharSet.Size; char ch = pwCharSet[(uint)uIndex]; if (pwProfile.NoRepeatingCharacters) { pwCharSet.Remove(ch); } return(ch); }
private static PwgError GenerateCustom(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crs, CustomPwGeneratorPool pwAlgorithmPool) { psOut = ProtectedString.Empty; Debug.Assert(pwProfile.GeneratorType == PasswordGeneratorType.Custom); if (pwAlgorithmPool == null) { return(PwgError.UnknownAlgorithm); } string strID = pwProfile.CustomAlgorithmUuid; if (string.IsNullOrEmpty(strID)) { Debug.Assert(false); return(PwgError.UnknownAlgorithm); } byte[] pbUuid = Convert.FromBase64String(strID); PwUuid uuid = new PwUuid(pbUuid); CustomPwGenerator pwg = pwAlgorithmPool.Find(uuid); if (pwg == null) { Debug.Assert(false); return(PwgError.UnknownAlgorithm); } ProtectedString pwd = pwg.Generate(pwProfile.CloneDeep(), crs); if (pwd == null) { return(PwgError.Unknown); } psOut = pwd; return(PwgError.Success); }
public static PwgError Generate(ProtectedString psOutBuffer, PwProfile pwProfile, byte[] pbUserEntropy, CustomPwGeneratorPool pwAlgorithmPool) { Debug.Assert(psOutBuffer != null); if(psOutBuffer == null) throw new ArgumentNullException("psOutBuffer"); Debug.Assert(pwProfile != null); if(pwProfile == null) throw new ArgumentNullException("pwProfile"); psOutBuffer.Clear(); CryptoRandomStream crs = CreateCryptoStream(pbUserEntropy); PwgError e = PwgError.Unknown; if(pwProfile.GeneratorType == PasswordGeneratorType.CharSet) e = CharSetBasedGenerator.Generate(psOutBuffer, pwProfile, crs); else if(pwProfile.GeneratorType == PasswordGeneratorType.Pattern) e = PatternBasedGenerator.Generate(psOutBuffer, pwProfile, crs); else if(pwProfile.GeneratorType == PasswordGeneratorType.Custom) e = GenerateCustom(psOutBuffer, pwProfile, crs, pwAlgorithmPool); else { Debug.Assert(false); } return e; }
internal static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { psOut = ProtectedString.Empty; if (pwProfile.Length == 0) { return(PwgError.Success); } PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString()); char[] vGenerated = new char[pwProfile.Length]; PwGenerator.PrepareCharSet(pcs, pwProfile); for (int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex) { char ch = PwGenerator.GenerateCharacter(pwProfile, pcs, crsRandomSource); if (ch == char.MinValue) { MemUtil.ZeroArray <char>(vGenerated); return(PwgError.TooFewCharacters); } vGenerated[nIndex] = ch; } byte[] pbUtf8 = StrUtil.Utf8.GetBytes(vGenerated); psOut = new ProtectedString(true, pbUtf8); MemUtil.ZeroByteArray(pbUtf8); MemUtil.ZeroArray <char>(vGenerated); return(PwgError.Success); }
public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource) { Random r = new Random((int)crsRandomSource.GetRandomUInt64()); var opt = new DiceWareOptions(prf.CustomAlgorithmOptions); string result = ""; int word = 0; for (int i = 0; i < 5 * opt.WordCount; i++) { word *= 10; word += (1 + r.Next(6)); if ((i + 1) % 5 == 0 && i > 0) { result += words[word]; result += " "; word = 0; } } return new ProtectedString(true, result.Trim()); }
public static PwProfile DeriveFromPassword(ProtectedString psPassword) { PwProfile pp = new PwProfile(); Debug.Assert(psPassword != null); if(psPassword == null) return pp; PwCharSet pcs = pp.CharSet; byte[] pbUTF8 = psPassword.ReadUtf8(); char[] vChars = Encoding.UTF8.GetChars(pbUTF8); pp.GeneratorType = PasswordGeneratorType.CharSet; pp.Length = (uint)vChars.Length; foreach(char ch in vChars) { if((ch >= 'A') && (ch <= 'Z')) pcs.Add(PwCharSet.UpperCase); else if((ch >= 'a') && (ch <= 'z')) pcs.Add(PwCharSet.LowerCase); else if((ch >= '0') && (ch <= '9')) pcs.Add(PwCharSet.Digits); else if((@"!#$%&'*+,./:;=?@^").IndexOf(ch) >= 0) pcs.Add(pcs.SpecialChars); else if(ch == ' ') pcs.Add(' '); else if(ch == '-') pcs.Add('-'); else if(ch == '_') pcs.Add('_'); else if(ch == '\"') pcs.Add(pcs.SpecialChars); else if(ch == '\\') pcs.Add(pcs.SpecialChars); else if((@"()[]{}<>").IndexOf(ch) >= 0) pcs.Add(PwCharSet.Brackets); else if((ch >= '~') && (ch <= 255)) pcs.Add(pcs.HighAnsiChars); else pcs.Add(ch); } Array.Clear(vChars, 0, vChars.Length); Array.Clear(pbUTF8, 0, pbUTF8.Length); return pp; }
internal static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { psOut = ProtectedString.Empty; string strPattern = pwProfile.Pattern; if (string.IsNullOrEmpty(strPattern)) { return(PwgError.Success); } CharStream cs = new CharStream(strPattern); LinkedList <char> llGenerated = new LinkedList <char>(); PwCharSet pcs = new PwCharSet(); while (true) { char ch = cs.ReadChar(); if (ch == char.MinValue) { break; } pcs.Clear(); if (ch == '\\') { ch = cs.ReadChar(); if (ch == char.MinValue) { return(PwgError.InvalidPattern); } pcs.Add(ch); // Allow "{...}" support and char check } else if (ch == '[') { if (!ReadCustomCharSet(cs, pcs)) { return(PwgError.InvalidPattern); } } else { if (!pcs.AddCharSet(ch)) { return(PwgError.InvalidPattern); } } int nCount = 1; if (cs.PeekChar() == '{') { nCount = ReadCount(cs); if (nCount < 0) { return(PwgError.InvalidPattern); } } for (int i = 0; i < nCount; ++i) { if (!PwGenerator.PrepareCharSet(pcs, pwProfile)) { return(PwgError.InvalidCharSet); } if (pwProfile.NoRepeatingCharacters) { foreach (char chUsed in llGenerated) { pcs.Remove(chUsed); } } char chGen = PwGenerator.GenerateCharacter(pcs, crsRandomSource); if (chGen == char.MinValue) { return(PwgError.TooFewCharacters); } llGenerated.AddLast(chGen); } } if (llGenerated.Count == 0) { return(PwgError.Success); } char[] v = new char[llGenerated.Count]; llGenerated.CopyTo(v, 0); if (pwProfile.PatternPermutePassword) { PwGenerator.Shuffle(v, crsRandomSource); } byte[] pbUtf8 = StrUtil.Utf8.GetBytes(v); psOut = new ProtectedString(true, pbUtf8); MemUtil.ZeroByteArray(pbUtf8); MemUtil.ZeroArray <char>(v); return(PwgError.Success); }
private void OnFileNew(object sender, EventArgs e) { if(!AppPolicy.Try(AppPolicyId.NewFile)) return; if(!AppPolicy.Try(AppPolicyId.SaveFile)) return; SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.CreateNewDatabase, KPRes.NewDatabaseFileName, UIUtil.CreateFileTypeFilter( AppDefs.FileExtension.FileExt, KPRes.KdbxFiles, true), 1, AppDefs.FileExtension.FileExt, AppDefs.FileDialogContext.Database); GlobalWindowManager.AddDialog(sfd.FileDialog); DialogResult dr = sfd.ShowDialog(); GlobalWindowManager.RemoveDialog(sfd.FileDialog); string strPath = sfd.FileName; if(dr != DialogResult.OK) return; KeyCreationForm kcf = new KeyCreationForm(); kcf.InitEx(IOConnectionInfo.FromPath(strPath), true); dr = kcf.ShowDialog(); if((dr == DialogResult.Cancel) || (dr == DialogResult.Abort)) { UIUtil.DestroyForm(kcf); return; } PwDocument dsPrevActive = m_docMgr.ActiveDocument; PwDatabase pd = m_docMgr.CreateNewDocument(true).Database; pd.New(IOConnectionInfo.FromPath(strPath), kcf.CompositeKey); UIUtil.DestroyForm(kcf); DatabaseSettingsForm dsf = new DatabaseSettingsForm(); dsf.InitEx(true, pd); dr = dsf.ShowDialog(); if((dr == DialogResult.Cancel) || (dr == DialogResult.Abort)) { m_docMgr.CloseDatabase(pd); try { m_docMgr.ActiveDocument = dsPrevActive; } catch(Exception) { } // Fails if no database is open now UpdateUI(false, null, true, null, true, null, false); UIUtil.DestroyForm(dsf); return; } UIUtil.DestroyForm(dsf); // AutoEnableVisualHiding(); PwGroup pg = new PwGroup(true, true, KPRes.General, PwIcon.Folder); // for(int i = 0; i < 30; ++i) pg.CustomData.Set("Test" + i.ToString("D2"), "12345"); pd.RootGroup.AddGroup(pg, true); pg = new PwGroup(true, true, KPRes.WindowsOS, PwIcon.DriveWindows); pd.RootGroup.AddGroup(pg, true); pg = new PwGroup(true, true, KPRes.Network, PwIcon.NetworkServer); pd.RootGroup.AddGroup(pg, true); pg = new PwGroup(true, true, KPRes.Internet, PwIcon.World); // pg.CustomData.Set("GroupTestItem", "TestValue"); pd.RootGroup.AddGroup(pg, true); pg = new PwGroup(true, true, KPRes.EMail, PwIcon.EMail); pd.RootGroup.AddGroup(pg, true); pg = new PwGroup(true, true, KPRes.Homebanking, PwIcon.Homebanking); pd.RootGroup.AddGroup(pg, true); PwEntry pe = new PwEntry(true, true); pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, KPRes.SampleEntry)); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName, KPRes.UserName)); pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl, PwDefs.HomepageUrl)); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword, KPRes.Password)); pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pd.MemoryProtection.ProtectNotes, KPRes.Notes)); pe.AutoType.Add(new AutoTypeAssociation(KPRes.TargetWindow, @"{USERNAME}{TAB}{PASSWORD}{TAB}{ENTER}")); // for(int i = 0; i < 30; ++i) pe.CustomData.Set("Test" + i.ToString("D2"), "12345"); pd.RootGroup.AddEntry(pe, true); pe = new PwEntry(true, true); pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, KPRes.SampleEntry + " #2")); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName, "Michael321")); pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl, @"http://keepass.info/help/kb/testform.html")); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword, "12345")); pe.AutoType.Add(new AutoTypeAssociation("*Test Form - KeePass*", string.Empty)); pd.RootGroup.AddEntry(pe, true); #if DEBUG Random r = Program.GlobalRandom; long lTimeMin = (new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).ToBinary(); long lTimeMax = (new DateTime(2030, 11, 25, 11, 58, 58, DateTimeKind.Utc)).ToBinary(); Debug.Assert(lTimeMin < lTimeMax); PwProfile prf = new PwProfile(); prf.CharSet = new PwCharSet(PwCharSet.UpperCase + PwCharSet.LowerCase + PwCharSet.Digits + PwCharSet.PrintableAsciiSpecial); prf.GeneratorType = PasswordGeneratorType.CharSet; for(uint iSamples = 0; iSamples < 1500; ++iSamples) { pg = pd.RootGroup.Groups.GetAt(iSamples % 5); pe = new PwEntry(true, true); ProtectedString ps; PwGenerator.Generate(out ps, prf, null, null); pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pd.MemoryProtection.ProtectTitle, ps.ReadString())); PwGenerator.Generate(out ps, prf, null, null); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pd.MemoryProtection.ProtectUserName, ps.ReadString())); PwGenerator.Generate(out ps, prf, null, null); pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pd.MemoryProtection.ProtectUrl, ps.ReadString())); PwGenerator.Generate(out ps, prf, null, null); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pd.MemoryProtection.ProtectPassword, ps.ReadString())); PwGenerator.Generate(out ps, prf, null, null); pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pd.MemoryProtection.ProtectNotes, ps.ReadString())); pe.CreationTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() * (lTimeMax - lTimeMin))); pe.LastModificationTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() * (lTimeMax - lTimeMin))); pe.LastAccessTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() * (lTimeMax - lTimeMin))); pe.ExpiryTime = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() * (lTimeMax - lTimeMin))); pe.LocationChanged = DateTime.FromBinary(lTimeMin + (long)(r.NextDouble() * (lTimeMax - lTimeMin))); pe.IconId = (PwIcon)r.Next(0, (int)PwIcon.Count); pg.AddEntry(pe, true); } pd.CustomData.Set("Sample Custom Data 1", "0123456789"); pd.CustomData.Set("Sample Custom Data 2", "\u00B5y data"); // pd.PublicCustomData.SetString("Sample Custom Data", "Sample Value"); #endif UpdateUI(true, null, true, null, true, null, true); if(this.FileCreated != null) { FileCreatedEventArgs ea = new FileCreatedEventArgs(pd); this.FileCreated(this, ea); } }
internal static PwgError Generate(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { psOut = ProtectedString.Empty; LinkedList <char> vGenerated = new LinkedList <char>(); PwCharSet pcsCurrent = new PwCharSet(); PwCharSet pcsCustom = new PwCharSet(); PwCharSet pcsUsed = new PwCharSet(); bool bInCharSetDef = false; string strPattern = ExpandPattern(pwProfile.Pattern); if (strPattern.Length == 0) { return(PwgError.Success); } CharStream csStream = new CharStream(strPattern); char ch = csStream.ReadChar(); while (ch != char.MinValue) { pcsCurrent.Clear(); bool bGenerateChar = false; if (ch == '\\') { ch = csStream.ReadChar(); if (ch == char.MinValue) // Backslash at the end { vGenerated.AddLast('\\'); break; } if (bInCharSetDef) { pcsCustom.Add(ch); } else { vGenerated.AddLast(ch); pcsUsed.Add(ch); } } else if (ch == '^') { ch = csStream.ReadChar(); if (ch == char.MinValue) // ^ at the end { vGenerated.AddLast('^'); break; } if (bInCharSetDef) { pcsCustom.Remove(ch); } } else if (ch == '[') { pcsCustom.Clear(); bInCharSetDef = true; } else if (ch == ']') { pcsCurrent.Add(pcsCustom.ToString()); bInCharSetDef = false; bGenerateChar = true; } else if (bInCharSetDef) { if (pcsCustom.AddCharSet(ch) == false) { pcsCustom.Add(ch); } } else if (pcsCurrent.AddCharSet(ch) == false) { vGenerated.AddLast(ch); pcsUsed.Add(ch); } else { bGenerateChar = true; } if (bGenerateChar) { PwGenerator.PrepareCharSet(pcsCurrent, pwProfile); if (pwProfile.NoRepeatingCharacters) { pcsCurrent.Remove(pcsUsed.ToString()); } char chGen = PwGenerator.GenerateCharacter(pwProfile, pcsCurrent, crsRandomSource); if (chGen == char.MinValue) { return(PwgError.TooFewCharacters); } vGenerated.AddLast(chGen); pcsUsed.Add(chGen); } ch = csStream.ReadChar(); } if (vGenerated.Count == 0) { return(PwgError.Success); } char[] vArray = new char[vGenerated.Count]; vGenerated.CopyTo(vArray, 0); if (pwProfile.PatternPermutePassword) { PwGenerator.ShufflePassword(vArray, crsRandomSource); } byte[] pbUtf8 = StrUtil.Utf8.GetBytes(vArray); psOut = new ProtectedString(true, pbUtf8); MemUtil.ZeroByteArray(pbUtf8); MemUtil.ZeroArray <char>(vArray); vGenerated.Clear(); return(PwgError.Success); }
/// <summary> /// Password generation function. /// </summary> /// <param name="prf">Password generation options chosen /// by the user. This may be <c>null</c>, if the default /// options should be used.</param> /// <param name="crsRandomSource">Source that the algorithm /// can use to generate random numbers.</param> /// <returns>Generated password or <c>null</c> in case /// of failure. If returning <c>null</c>, the caller assumes /// that an error message has already been shown to the user.</returns> public abstract ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource);
/// <summary> /// Initialize this password generator form instance. /// </summary> /// <param name="pwInitial">Initial options (may be <c>null</c>).</param> public void InitEx(PwProfile pwInitial, bool bCanAccept, bool bForceInTaskbar) { m_optInitial = pwInitial; m_bCanAccept = bCanAccept; m_bForceInTaskbar = bForceInTaskbar; }
internal static void PrepareCharSet(PwCharSet pwCharSet, PwProfile pwProfile) { pwCharSet.Remove(PwCharSet.Invalid); if(pwProfile.ExcludeLookAlike) pwCharSet.Remove(PwCharSet.LookAlike); if(pwProfile.ExcludeCharacters.Length > 0) pwCharSet.Remove(pwProfile.ExcludeCharacters); }
private void OnBtnOK(object sender, EventArgs e) { m_optSelected = GetGenerationOptions(); }
private static PwgError GenerateCustom(out ProtectedString psOut, PwProfile pwProfile, CryptoRandomStream crs, CustomPwGeneratorPool pwAlgorithmPool) { psOut = ProtectedString.Empty; Debug.Assert(pwProfile.GeneratorType == PasswordGeneratorType.Custom); if(pwAlgorithmPool == null) return PwgError.UnknownAlgorithm; string strID = pwProfile.CustomAlgorithmUuid; if(string.IsNullOrEmpty(strID)) { Debug.Assert(false); return PwgError.UnknownAlgorithm; } byte[] pbUuid = Convert.FromBase64String(strID); PwUuid uuid = new PwUuid(pbUuid); CustomPwGenerator pwg = pwAlgorithmPool.Find(uuid); if(pwg == null) { Debug.Assert(false); return PwgError.UnknownAlgorithm; } ProtectedString pwd = pwg.Generate(pwProfile.CloneDeep(), crs); if(pwd == null) return PwgError.Unknown; psOut = pwd; return PwgError.Success; }
public static PwgError Generate(ProtectedString psOutBuffer, PwProfile pwProfile, CryptoRandomStream crsRandomSource) { LinkedList<char> vGenerated = new LinkedList<char>(); PwCharSet pcsCurrent = new PwCharSet(); PwCharSet pcsCustom = new PwCharSet(); PwCharSet pcsUsed = new PwCharSet(); bool bInCharSetDef = false; string strPattern = ExpandPattern(pwProfile.Pattern); if(strPattern.Length == 0) return PwgError.Success; CharStream csStream = new CharStream(strPattern); char ch = csStream.ReadChar(); while(ch != char.MinValue) { pcsCurrent.Clear(); bool bGenerateChar = false; if(ch == '\\') { ch = csStream.ReadChar(); if(ch == char.MinValue) // Backslash at the end { vGenerated.AddLast('\\'); break; } if(bInCharSetDef) pcsCustom.Add(ch); else { vGenerated.AddLast(ch); pcsUsed.Add(ch); } } else if(ch == '[') { pcsCustom.Clear(); bInCharSetDef = true; } else if(ch == ']') { pcsCurrent.Add(pcsCustom.ToString()); bInCharSetDef = false; bGenerateChar = true; } else if(bInCharSetDef) { if(pcsCustom.AddCharSet(ch) == false) pcsCustom.Add(ch); } else if(pcsCurrent.AddCharSet(ch) == false) { vGenerated.AddLast(ch); pcsUsed.Add(ch); } else bGenerateChar = true; if(bGenerateChar) { PwGenerator.PrepareCharSet(pcsCurrent, pwProfile); if(pwProfile.NoRepeatingCharacters) pcsCurrent.Remove(pcsUsed.ToString()); char chGen = PwGenerator.GenerateCharacter(pwProfile, pcsCurrent, crsRandomSource); if(chGen == char.MinValue) return PwgError.TooFewCharacters; vGenerated.AddLast(chGen); pcsUsed.Add(chGen); } ch = csStream.ReadChar(); } if(vGenerated.Count == 0) return PwgError.Success; char[] vArray = new char[vGenerated.Count]; vGenerated.CopyTo(vArray, 0); if(pwProfile.PatternPermutePassword) PwGenerator.ShufflePassword(vArray, crsRandomSource); byte[] pbUtf8 = Encoding.UTF8.GetBytes(vArray); psOutBuffer.SetString(Encoding.UTF8.GetString(pbUtf8, 0, pbUtf8.Length)); Array.Clear(pbUtf8, 0, pbUtf8.Length); Array.Clear(vArray, 0, vArray.Length); vGenerated.Clear(); return PwgError.Success; }
public static PwProfile DeriveFromPassword(ProtectedString psPassword) { PwProfile pp = new PwProfile(); Debug.Assert(psPassword != null); if (psPassword == null) { return(pp); } PwCharSet pcs = pp.CharSet; byte[] pbUTF8 = psPassword.ReadUtf8(); char[] vChars = Encoding.UTF8.GetChars(pbUTF8); pp.GeneratorType = PasswordGeneratorType.CharSet; pp.Length = (uint)vChars.Length; foreach (char ch in vChars) { if ((ch >= 'A') && (ch <= 'Z')) { pcs.Add(PwCharSet.UpperCase); } else if ((ch >= 'a') && (ch <= 'z')) { pcs.Add(PwCharSet.LowerCase); } else if ((ch >= '0') && (ch <= '9')) { pcs.Add(PwCharSet.Digits); } else if ((@"!#$%&'*+,./:;=?@^").IndexOf(ch) >= 0) { pcs.Add(pcs.SpecialChars); } else if (ch == ' ') { pcs.Add(' '); } else if (ch == '-') { pcs.Add('-'); } else if (ch == '_') { pcs.Add('_'); } else if (ch == '\"') { pcs.Add(pcs.SpecialChars); } else if (ch == '\\') { pcs.Add(pcs.SpecialChars); } else if ((@"()[]{}<>").IndexOf(ch) >= 0) { pcs.Add(PwCharSet.Brackets); } else if ((ch >= '~') && (ch <= 255)) { pcs.Add(pcs.HighAnsiChars); } else { pcs.Add(ch); } } Array.Clear(vChars, 0, vChars.Length); Array.Clear(pbUTF8, 0, pbUTF8.Length); return(pp); }
private PwProfile GetGenerationOptions() { PwProfile opt = new PwProfile(); opt.Name = m_cmbProfiles.Text; if(m_rbStandardCharSet.Checked) opt.GeneratorType = PasswordGeneratorType.CharSet; else if(m_rbPattern.Checked) opt.GeneratorType = PasswordGeneratorType.Pattern; else if(m_rbCustom.Checked) opt.GeneratorType = PasswordGeneratorType.Custom; opt.Length = (uint)m_numGenChars.Value; opt.CharSet = new PwCharSet(); if(m_cbUpperCase.Checked) opt.CharSet.Add(PwCharSet.UpperCase); if(m_cbLowerCase.Checked) opt.CharSet.Add(PwCharSet.LowerCase); if(m_cbDigits.Checked) opt.CharSet.Add(PwCharSet.Digits); if(m_cbSpecial.Checked) opt.CharSet.Add(PwCharSet.SpecialChars); if(m_cbHighAnsi.Checked) opt.CharSet.Add(PwCharSet.HighAnsiChars); if(m_cbMinus.Checked) opt.CharSet.Add('-'); if(m_cbUnderline.Checked) opt.CharSet.Add('_'); if(m_cbSpace.Checked) opt.CharSet.Add(' '); if(m_cbBrackets.Checked) opt.CharSet.Add(PwCharSet.Brackets); opt.CharSet.Add(m_tbCustomChars.Text); opt.Pattern = m_tbPattern.Text; opt.PatternPermutePassword = m_cbPatternPermute.Checked; opt.CollectUserEntropy = m_cbEntropy.Checked; opt.ExcludeLookAlike = m_cbExcludeLookAlike.Checked; opt.NoRepeatingCharacters = m_cbNoRepeat.Checked; opt.ExcludeCharacters = m_tbExcludeChars.Text; CustomPwGenerator pwg = GetPwGenerator(); opt.CustomAlgorithmUuid = ((pwg != null) ? Convert.ToBase64String( pwg.Uuid.UuidBytes) : string.Empty); if((pwg != null) && m_dictCustomOptions.ContainsKey(pwg)) opt.CustomAlgorithmOptions = (m_dictCustomOptions[pwg] ?? string.Empty); else opt.CustomAlgorithmOptions = string.Empty; return opt; }
/// <summary> /// Generate a random dictionary password. /// </summary> /// <param name="prf">The password profile to use.</param> /// <param name="crsRandomSource">The cryptographic stream.</param> /// <returns>A generated ProtectedString password.</returns> public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource) { // Get the generator options. GeneratorOptions options = new GeneratorOptions(prf.CustomAlgorithmOptions); // Check if a word dictionary has already been loaded, if not, load it. if (_wordDictionary == null || _currentWordLength != options.WordLength) { _wordDictionary = ExtractWordDictionary(options.WordLength); _currentWordLength = options.WordLength; } // Get a random word from the dictionary RandomNumber randomNumber = new RandomNumber(crsRandomSource); string password = _wordDictionary.Count > 0 ? _wordDictionary[randomNumber.Next(_wordDictionary.Count)] : string.Empty; _wordDictionary.Remove(password); // Substitute characters if specified. if (options.SubstituteCharacters && !string.IsNullOrEmpty(options.SubstitutionList)) password = SubstituteCharacters(password, options.SubstitutionList); // Capitalize if necessary if (options.CapitalizationType != CapitalizationTypes.None) password = CapitalizePassword(password, options.CapitalizationType, randomNumber); return new ProtectedString(false, password); }
private void SetGenerationOptions(PwProfile opt) { bool bPrevInit = m_bBlockUIUpdate; m_bBlockUIUpdate = true; m_rbStandardCharSet.Checked = (opt.GeneratorType == PasswordGeneratorType.CharSet); m_rbPattern.Checked = (opt.GeneratorType == PasswordGeneratorType.Pattern); m_rbCustom.Checked = (opt.GeneratorType == PasswordGeneratorType.Custom); m_numGenChars.Value = opt.Length; PwCharSet pcs = new PwCharSet(opt.CharSet.ToString()); m_cbUpperCase.Checked = pcs.RemoveIfAllExist(PwCharSet.UpperCase); m_cbLowerCase.Checked = pcs.RemoveIfAllExist(PwCharSet.LowerCase); m_cbDigits.Checked = pcs.RemoveIfAllExist(PwCharSet.Digits); m_cbSpecial.Checked = pcs.RemoveIfAllExist(PwCharSet.SpecialChars); m_cbHighAnsi.Checked = pcs.RemoveIfAllExist(PwCharSet.HighAnsiChars); m_cbMinus.Checked = pcs.RemoveIfAllExist("-"); m_cbUnderline.Checked = pcs.RemoveIfAllExist("_"); m_cbSpace.Checked = pcs.RemoveIfAllExist(" "); m_cbBrackets.Checked = pcs.RemoveIfAllExist(PwCharSet.Brackets); m_tbCustomChars.Text = pcs.ToString(); m_tbPattern.Text = opt.Pattern; m_cbPatternPermute.Checked = opt.PatternPermutePassword; m_cbEntropy.Checked = opt.CollectUserEntropy; m_cbExcludeLookAlike.Checked = opt.ExcludeLookAlike; m_cbNoRepeat.Checked = opt.NoRepeatingCharacters; m_tbExcludeChars.Text = opt.ExcludeCharacters; SelectCustomGenerator(opt.CustomAlgorithmUuid, opt.CustomAlgorithmOptions); m_bBlockUIUpdate = bPrevInit; }
internal static ProtectedString GenerateAcceptable(PwProfile prf, byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx) { bool b = false; return GenerateAcceptable(prf, pbUserEntropy, peOptCtx, pdOptCtx, ref b); }
internal static ProtectedString GenerateAcceptable(PwProfile prf, byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx, ref bool bAcceptAlways) { ProtectedString ps = ProtectedString.Empty; SprContext ctx = new SprContext(peOptCtx, pdOptCtx, SprCompileFlags.NonActive, false, false); bool bAcceptable = false; while(!bAcceptable) { bAcceptable = true; PwGenerator.Generate(out ps, prf, pbUserEntropy, Program.PwGeneratorPool); if(ps == null) { Debug.Assert(false); ps = ProtectedString.Empty; } if(bAcceptAlways) { } else { string str = ps.ReadString(); string strCmp = SprEngine.Compile(str, ctx); if(str != strCmp) { if(prf.GeneratorType == PasswordGeneratorType.CharSet) bAcceptable = false; // Silently try again else { string strText = str + MessageService.NewParagraph + KPRes.GenPwSprVariant + MessageService.NewParagraph + KPRes.GenPwAccept; if(!MessageService.AskYesNo(strText, null, false)) bAcceptable = false; else bAcceptAlways = true; } } } } return ps; }
private PwProfile GetGenerationOptions() { PwProfile opt = new PwProfile(); opt.Name = m_cmbProfiles.Text; if(m_rbStandardCharSet.Checked) opt.GeneratorType = PasswordGeneratorType.CharSet; else if(m_rbPattern.Checked) opt.GeneratorType = PasswordGeneratorType.Pattern; opt.Length = (uint)m_numGenChars.Value; opt.CharSet = new PwCharSet(); if(m_cbUpperCase.Checked) opt.CharSet.Add(PwCharSet.UpperCase); if(m_cbLowerCase.Checked) opt.CharSet.Add(PwCharSet.LowerCase); if(m_cbDigits.Checked) opt.CharSet.Add(PwCharSet.Digits); if(m_cbSpecial.Checked) opt.CharSet.Add(opt.CharSet.SpecialChars); if(m_cbHighAnsi.Checked) opt.CharSet.Add(opt.CharSet.HighAnsiChars); if(m_cbMinus.Checked) opt.CharSet.Add('-'); if(m_cbUnderline.Checked) opt.CharSet.Add('_'); if(m_cbSpace.Checked) opt.CharSet.Add(' '); if(m_cbBrackets.Checked) opt.CharSet.Add(PwCharSet.Brackets); opt.CharSet.Add(m_tbCustomChars.Text); opt.Pattern = m_tbPattern.Text; opt.PatternPermutePassword = m_cbPatternPermute.Checked; opt.CollectUserEntropy = m_cbEntropy.Checked; opt.ExcludeLookAlike = m_cbExcludeLookAlike.Checked; opt.NoRepeatingCharacters = m_cbNoRepeat.Checked; opt.ExcludeCharacters = m_tbExcludeChars.Text; return opt; }