private void GeneratePreviewPasswords() { m_pbPreview.Value = 0; m_tbPreview.Text = string.Empty; PwProfile pwOpt = GetGenerationOptions(); StringBuilder sbList = new StringBuilder(); Cursor cNormalCursor = this.Cursor; this.Cursor = Cursors.WaitCursor; for (uint i = 0; i < MaxPreviewPasswords; ++i) { Application.DoEvents(); ProtectedString psNew = new ProtectedString(false); PwGenerator.Generate(psNew, pwOpt, null, Program.PwGeneratorPool); sbList.AppendLine(psNew.ReadString()); m_pbPreview.Value = (int)((100 * i) / MaxPreviewPasswords); } m_pbPreview.Value = 100; m_tbPreview.Text = sbList.ToString(); this.Cursor = cNormalCursor; }
private void GeneratePassword(Request r, Response resp, Aes aes) { if (!VerifyRequest(r, aes)) { return; } byte[] pbEntropy = null; ProtectedString psNew; PwProfile autoProfile = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile; PwGenerator.Generate(out psNew, autoProfile, pbEntropy, Program.PwGeneratorPool); byte[] pbNew = psNew.ReadUtf8(); if (pbNew != null) { uint uBits = QualityEstimation.EstimatePasswordBits(pbNew); ResponseEntry item = new ResponseEntry(Request.GENERATE_PASSWORD, uBits.ToString(), StrUtil.Utf8.GetString(pbNew), Request.GENERATE_PASSWORD, null); resp.Entries.Add(item); resp.Success = true; resp.Count = 1; MemUtil.ZeroByteArray(pbNew); } resp.Id = r.Id; SetResponseVerifier(resp, aes); foreach (var entry in resp.Entries) { entry.Name = CryptoTransform(entry.Name, false, true, aes, CMode.ENCRYPT); entry.Login = CryptoTransform(entry.Login, false, true, aes, CMode.ENCRYPT); entry.Uuid = CryptoTransform(entry.Uuid, false, true, aes, CMode.ENCRYPT); entry.Password = CryptoTransform(entry.Password, false, true, aes, CMode.ENCRYPT); } }
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)); } var persistence = new ConfigurationPersistence(); var config = persistence.LoadFromUserFile(); InitWuerfelwareFileReaderIfNecessary(); // no entries? if (WuerfelwareFileReader.MaxValidIndex < 0) { throw new IndexOutOfRangeException("Word list ist empty"); } var resultingWords = new List <string>(); for (var i = 0; i < Math.Min(Math.Max(Constants.MinWordsPerPassphrase, config.WordCount), Constants.MaxWordsPerPassphrase); i++) { var index = GetRandomIndex(crsRandomSource, (ulong)WuerfelwareFileReader.EntryCount); // note: we checked earlier that entryCount is >= 0 // index cannot be higher than int.MaxValue since MaxIndex is of type int resultingWords.Add(WuerfelwareFileReader.GetEntry((int)index)); } return(new ProtectedString(false, string.Join(" ", resultingWords.ToArray()))); }
public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource) { var profile = prf; if (profile == null) { profile = new PwProfile(); } // Load the phrase template from config. var conf = new Config(profile.CustomAlgorithmOptions); // Create and cache the dictionary. // Important note: do not cache the CryptoRandomStream or ReadablePassphraseGenerator // If you do, the CryptoRandomStream is disposed after the method returns, and you end up with very deterministic random numbers. // This can manifest itself as the name sandom words are generated in the Preview tab in KeeyPass's Generate Password form. // OR in more recent version of KeePass, you get an ObjectDisposedException var dict = GetDictionary(conf); var generator = new MurrayGrant.ReadablePassphrase.ReadablePassphraseGenerator(dict, new KeePassRandomSource(crsRandomSource)); if (conf.Mutator != MutatorOption.None) { return(GenerateForMutators(generator, conf)); } else if (Environment.OSVersion.Platform == PlatformID.Win32NT) { return(GenerateSecure(generator, conf)); } else { return(GenerateNotSoSecure(generator, conf)); } }
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_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(pcs.SpecialChars); m_cbHighAnsi.Checked = pcs.RemoveIfAllExist(pcs.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; m_bBlockUIUpdate = bPrevInit; }
private void PasswordGeneratorCommand(RowObject rowObject) { var passwordGenerator = new PwGeneratorForm(); PwProfile profile = null; if (!rowObject.Value.IsEmpty) { profile = KeePassLib.Cryptography.PasswordGenerator.PwProfile.DeriveFromPassword(rowObject.Value); } passwordGenerator.InitEx(profile, true, false); if (passwordGenerator.ShowDialog() == DialogResult.OK) { // Logic copied from PwEntryForm.OnPwGenOpen (PwEntryForm.cs) var entropy = EntropyForm.CollectEntropyIfEnabled(passwordGenerator.SelectedProfile); ProtectedString newPassword; PwGenerator.Generate(out newPassword, passwordGenerator.SelectedProfile, entropy, KeePass.Program.PwGeneratorPool); SetFieldValue(rowObject, newPassword); RefreshObject(rowObject); } UIUtil.DestroyForm(passwordGenerator); }
private void GeneratePreviewPasswords() { m_pbPreview.Value = 0; m_tbPreview.Text = string.Empty; PwProfile pwOpt = GetGenerationOptions(); StringBuilder sbList = new StringBuilder(); Cursor cNormalCursor = this.Cursor; this.Cursor = Cursors.WaitCursor; uint n = MaxPreviewPasswords; if ((pwOpt.GeneratorType == PasswordGeneratorType.Custom) && string.IsNullOrEmpty(pwOpt.CustomAlgorithmUuid)) { n = 0; } for (uint i = 0; i < n; ++i) { Application.DoEvents(); ProtectedString psNew; PwGenerator.Generate(out psNew, pwOpt, null, Program.PwGeneratorPool); sbList.AppendLine(psNew.ReadString()); m_pbPreview.Value = (int)((100 * i) / MaxPreviewPasswords); } m_pbPreview.Value = 100; UIUtil.SetMultilineText(m_tbPreview, sbList.ToString()); this.Cursor = cNormalCursor; }
internal static ProtectedString GenerateAcceptable(PwProfile prf, byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx) { bool b = false; return(GenerateAcceptable(prf, pbUserEntropy, peOptCtx, pdOptCtx, ref b)); }
//Add single password profile to global configuration public static void AddDBProfile(this List <PwProfile> profiles, PwProfile profile) { PwProfile myProfile = profile.CloneDeep(); myProfile.Name += Config.ProfileDBOnly; profiles.Add(myProfile); }
private void ProfileClicked(object sender, ToolStripItemClickedEventArgs e) { if ((m_pweForm == null) || string.IsNullOrEmpty(e.ClickedItem.Text)) { return; } List <PwProfile> profiles = PwGeneratorUtil.GetAllProfiles(false); string prof = e.ClickedItem.Text.Replace("&", ""); m_pweForm.UpdateEntryStrings(true, true); PwProfile profile = profiles.Find(x => x.Name == prof); if (profile != null) { m_pweForm.EntryStrings.Set(Config.ProfileLastUsedProfile, new ProtectedString(false, prof)); } else if (prof == "(" + KPRes.AutoGeneratedPasswordSettings + ")") { m_pweForm.EntryStrings.Set(Config.ProfileLastUsedProfile, new ProtectedString(false, Config.ProfileAutoGenerated)); } else { m_pweForm.EntryStrings.Remove(Config.ProfileLastUsedProfile); } m_pweForm.UpdateEntryStrings(false, true); }
private static string GeneratePassword(string strProfile, SprContext ctx) { PwProfile prf = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile; if (!string.IsNullOrEmpty(strProfile)) { if (strProfile == @"~") { prf = PwProfile.DeriveFromPassword(ctx.Entry.Strings.GetSafe( PwDefs.PasswordField)); } else { List <PwProfile> lPrf = PwGeneratorUtil.GetAllProfiles(false); foreach (PwProfile p in lPrf) { if (strProfile.Equals(p.Name, StrUtil.CaseIgnoreCmp)) { prf = p; break; } } } } PwEntry peCtx = ((ctx != null) ? ctx.Entry : null); PwDatabase pdCtx = ((ctx != null) ? ctx.Database : null); ProtectedString ps = PwGeneratorUtil.GenerateAcceptable( prf, null, peCtx, pdCtx); return(ps.ReadString()); }
private void OnProfilesDynamicMenuClick(object sender, DynamicMenuEventArgs e) { PwProfile pwp = null; if (e.ItemName == DeriveFromPrevious) { pwp = PwProfile.DeriveFromPassword(current_password_field.TextEx); } else { foreach (PwProfile pwgo in Program.Config.PasswordGenerator.UserProfiles) { if (pwgo.Name == e.ItemName) { pwp = pwgo; break; } } } if (pwp != null) { ProtectedString psNew; PwGenerator.Generate(out psNew, pwp, null, m_host.PwGeneratorPool); current_password_confirm_field.TextEx = current_password_field.TextEx = psNew; } else { Debug.Assert(false); } }
private void PCADialog_Shown(object sender, EventArgs e) { rtbSequence_TextChanged(null, null); PwProfile PPSProfile = null; string PPSProfileName = m_pcadata.Strings.ReadSafe(Config.ProfileLastUsedProfile); if (PPSProfileName == Config.ProfileAutoGenerated) { PPSProfile = Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile; } else { PPSProfile = PwGeneratorUtil.GetAllProfiles(false).Find(X => X.Name == PPSProfileName); } if (PPSProfile != null) { m_Profile = PPSProfile; CreateNewPassword(PPSProfile); } else { CreateNewPassword(PwProfile.DeriveFromPassword(m_pcadata.OldPassword)); } HandleURLFields(); }
private void OnBtnProfileSave(object sender, EventArgs e) { List <string> lNames = new List <string>(); lNames.Add(AutoGeneratedMeta); foreach (PwProfile pwExisting in Program.Config.PasswordGenerator.UserProfiles) { lNames.Add(pwExisting.Name); } SingleLineEditForm slef = new SingleLineEditForm(); slef.InitEx(KPRes.GenProfileSave, KPRes.GenProfileSaveDesc, KPRes.GenProfileSaveDescLong, Properties.Resources.B48x48_KGPG_Gen, string.Empty, lNames.ToArray()); if (slef.ShowDialog() == DialogResult.OK) { string strProfile = slef.ResultString; PwProfile pwCurrent = GetGenerationOptions(); pwCurrent.Name = strProfile; if (strProfile.Equals(CustomMeta) || strProfile.Equals(DeriveFromPrevious) || (strProfile.Length == 0)) { MessageService.ShowWarning(KPRes.FieldNameInvalid); } else if (strProfile == AutoGeneratedMeta) { pwCurrent.Name = string.Empty; Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile = pwCurrent; m_cmbProfiles.SelectedIndex = m_cmbProfiles.FindString(AutoGeneratedMeta); } else { bool bExists = false; for (int i = 0; i < Program.Config.PasswordGenerator.UserProfiles.Count; ++i) { if (Program.Config.PasswordGenerator.UserProfiles[i].Name == strProfile) { Program.Config.PasswordGenerator.UserProfiles[i] = pwCurrent; m_cmbProfiles.SelectedIndex = m_cmbProfiles.FindString(strProfile); bExists = true; } } if (bExists == false) { Program.Config.PasswordGenerator.UserProfiles.Add(pwCurrent); m_cmbProfiles.Items.Add(strProfile); m_cmbProfiles.SelectedIndex = m_cmbProfiles.Items.Count - 1; } } } EnableControlsEx(false); }
private static void GenPw(CommandLineArgs args) { List <PwProfile> l = PwGeneratorUtil.GetAllProfiles(false); PwProfile pp = null; string strProfile = args[ParamProfile]; if (!string.IsNullOrEmpty(strProfile)) { foreach (PwProfile ppEnum in l) { if (strProfile.Equals(ppEnum.Name, StrUtil.CaseIgnoreCmp)) { pp = ppEnum; break; } } } if (pp == null) { pp = new PwProfile(); } string strCount = args[ParamCount]; int iCount = 1; if (!string.IsNullOrEmpty(strCount)) { if (!int.TryParse(strCount, out iCount)) { iCount = 1; } } if (iCount < 0) { iCount = 1; } for (int i = 0; i < iCount; ++i) { try { ProtectedString ps; PwGenerator.Generate(out ps, pp, null, KeePass.Program.PwGeneratorPool); if (ps != null) { string str = ps.ReadString(); if (!string.IsNullOrEmpty(str)) { Console.WriteLine(str); } } } catch (Exception) { } } }
//Convert passwort profile to atring public static string Serialize(this PwProfile profile) { using (StringWriter writer = new StringWriter()) { XmlSerializer profSerialize = new XmlSerializer(typeof(PwProfile)); profSerialize.Serialize(writer, profile); return(writer.ToString()); } }
private bool AddAdditionalChars(PwProfile p, string sAdditionalChars) { if (!string.IsNullOrEmpty(sAdditionalChars)) { p.Pattern += "[" + sAdditionalChars + "]{1}"; return(true); } return(false); }
private PwProfile InitProfile(PwProfile prf) { PwProfile p = prf.CloneDeep(); p.GeneratorType = PasswordGeneratorType.Pattern; p.PatternPermutePassword = true; p.Pattern = string.Empty; return(p); }
internal static ProtectedString GenerateAcceptable(PwProfile prf, byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx, bool bShowErrorUI) { bool bAcceptAlways = false; string strError; return(GenerateAcceptable(prf, pbUserEntropy, peOptCtx, pdOptCtx, bShowErrorUI, ref bAcceptAlways, out strError)); }
private string GetAdditionalChars(PwProfile prf) { string sAdditionalChars = string.Empty; for (int i = 0; i < prf.CharSetAdditional.Length; i++) { sAdditionalChars += "\\" + prf.CharSetAdditional[i]; //In a pattern, every character has to be escaped } return(sAdditionalChars); }
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 + StrUtil.NewParagraph + KPRes.GenPwSprVariant + StrUtil.NewParagraph + KPRes.GenPwAccept; if (!MessageService.AskYesNo(strText, null, false)) { bAcceptable = false; } else { bAcceptAlways = true; } } } } } return(ps); }
//Update list of database specific password profiles after closing password generator form private void UpdateDBProfiles(List <PwProfile> oldProfiles, List <PwProfile> newProfiles, out bool changed) { changed = false; if ((m_host.Database == null) || !m_host.Database.IsOpen) { return; } if (oldProfiles.Count != newProfiles.Count) { changed = true; m_host.Database.RemoveDBProfiles(); foreach (PwProfile profile in newProfiles) { profile.CopyTo(m_host.Database); } return; } for (int i = 0; i < newProfiles.Count; i++) { PwProfile profile = newProfiles[i].CloneDeep(); if (profile.IsDBOnlyProfile()) { profile.Name = profile.Name.Substring(0, profile.Name.Length - Config.ProfileDBOnly.Length); } PwProfile oldProfile = oldProfiles.Find(x => x.Name == profile.Name); changed |= !profile.IsEqual(oldProfile); if (changed) { break; } } for (int i = 0; i < oldProfiles.Count; i++) { PwProfile profile = oldProfiles[i].CloneDeep(); if (!profile.IsDBOnlyProfile()) { profile.Name += Config.ProfileDBOnly; } PwProfile newProfile = newProfiles.Find(x => x.Name == profile.Name); changed |= !profile.IsEqual(newProfile); if (changed) { break; } } if (!changed) { return; } m_host.Database.RemoveDBProfiles(); foreach (PwProfile profile in newProfiles) { profile.CopyTo(m_host.Database); } }
//Convert string to password profile public static PwProfile Deserialize(string profileData) { try { XmlSerializer profDeserialize = new XmlSerializer(typeof(PwProfile)); PwProfile profile = (PwProfile)profDeserialize.Deserialize(new StringReader(profileData)); return(profile); } catch (Exception) { } return(null); }
private void OnGenDeriveFromPrevious(object sender, EventArgs e) { ProtectedString ps = GetPassword(); if (ps == null) { Debug.Assert(false); return; } GenerateAndSetPassword(PwProfile.DeriveFromPassword(ps)); }
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); }
private void GenerateAndSetPassword(PwProfile prf) { if (prf == null) { Debug.Assert(false); return; } byte[] pbEntropy = EntropyForm.CollectEntropyIfEnabled(prf); PwEntry pe = ((m_fGetContextEntry != null) ? m_fGetContextEntry() : null); SetPassword(PwGeneratorUtil.GenerateAcceptable(prf, pbEntropy, pe, m_pdContext, true)); }
/// <summary> /// Generates and returns a password as a protected string. /// </summary> /// <param name="prf">Password profile.</param> /// <param name="crsRandomSource">Cryptographic random source.</param> /// <returns>The generated password.</returns> public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource) { UserConfig config = UserConfig.Deserialize(prf.CustomAlgorithmOptions); SystemConfig sysConfig = new SystemConfig(); RandomUtil random = new RandomUtil(crsRandomSource); IRepositoryFactory factory = new FileRepositoryFactory(config, sysConfig); IPhraseRepository repo = factory.Make(random); ISpecialCharsRepository specialCharsRepo = factory.MakeSpecialChars(random); IPhraseGenerator generator = new PhraseGenerator(config, repo, specialCharsRepo); return(generator.Generate()); }
private void GeneratePassword(Request r, Response resp, Aes aes) { if (!VerifyRequest(r, aes)) { return; } byte[] pbEntropy = null; ProtectedString psNew = null; if (r.PasswordType == PasswordGeneratorType.DEFAULT) { PwProfile autoProfile = new PwProfile(); PwGenerator.Generate(out psNew, autoProfile, pbEntropy, Program.PwGeneratorPool); } else if (r.PasswordType == PasswordGeneratorType.PATTERN) { PwProfile patternProfile = new PwProfile(); patternProfile.Pattern = r.PasswordPattern; patternProfile.PatternPermutePassword = true; patternProfile.GeneratorType = KeePassLib.Cryptography.PasswordGenerator.PasswordGeneratorType.Pattern; PwGenerator.Generate(out psNew, patternProfile, pbEntropy, Program.PwGeneratorPool); } else { // TODO finish this } byte[] pbNew = psNew.ReadUtf8(); if (pbNew != null) { uint uBits = QualityEstimation.EstimatePasswordBits(pbNew); ResponseEntry item = new ResponseEntry(Request.GENERATE_PASSWORD, uBits.ToString(), StrUtil.Utf8.GetString(pbNew), Request.GENERATE_PASSWORD, null); resp.Entries.Add(item); resp.Success = true; resp.Count = 1; MemUtil.ZeroByteArray(pbNew); } resp.Id = r.Id; SetResponseVerifier(resp, aes); foreach (var entry in resp.Entries) { entry.Name = CryptoTransform(entry.Name, false, true, aes, CMode.ENCRYPT); entry.Login = CryptoTransform(entry.Login, false, true, aes, CMode.ENCRYPT); entry.Uuid = CryptoTransform(entry.Uuid, false, true, aes, CMode.ENCRYPT); entry.Password = CryptoTransform(entry.Password, false, true, aes, CMode.ENCRYPT); } }
private void FinalizePattern(PwProfile p, string sPattern, string sAdditionalChars, int iLength, out bool bSuccess) { bSuccess = false; if (iLength < 0) { return; //Already longer than allowed } bSuccess = true; if (iLength > 0) { sAdditionalChars = "[" + sPattern + sAdditionalChars + "]{" + iLength.ToString().Trim() + "}"; p.Pattern += sAdditionalChars; } }