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);
        }
Example #2
0
        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;
        }
Example #3
0
        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;
        }
Example #4
0
        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);
            }
        }
Example #5
0
        private static string ReplaceNewPasswordPlaceholder(string strText,
                                                            PwEntry pe, PwDatabase pd, SprContentFlags cf)
        {
            if ((pe == null) || (pd == null))
            {
                return(strText);
            }

            string str = strText;

            const string strNewPwPlh = @"{NEWPASSWORD}";

            if (str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
            {
                ProtectedString psAutoGen = new ProtectedString(
                    pd.MemoryProtection.ProtectPassword);
                PwgError e = PwGenerator.Generate(psAutoGen,
                                                  Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile,
                                                  null, Program.PwGeneratorPool);

                if (e == PwgError.Success)
                {
                    pe.CreateBackup();
                    pe.Strings.Set(PwDefs.PasswordField, psAutoGen);
                    pd.Modified = true;

                    string strIns = SprEngine.TransformContent(psAutoGen.ReadString(), cf);
                    str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
                }
            }

            return(str);
        }
Example #6
0
        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);
            }
        }
Example #7
0
        public void handle_keyboard_shortcut_quick(object sender, KeyPressedEventArgs e)
        {
            ProtectedString str;

            PwGenerator.Generate(out str, Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile, null, Program.PwGeneratorPool);
            Clipboard.SetText(str.ReadString());
            quick_anim = 3;
        }
Example #8
0
        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) { }
            }
        }
Example #9
0
        protected void GenerateStrongPassword()
        {
            string password = PwGenerator.Generate(15, true, false, true).ReadString();
            Thread thread   = new Thread(() => Clipboard.SetText(password));

            thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
            thread.Start();
            thread.Join();
        }
        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);
        }
Example #11
0
        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);
            }
        }
        public string GeneratePassword(PasswordGenerationOptions options)
        {
            var pwProfile = new PwProfile
            {
                GeneratorType = PasswordGeneratorType.CharSet,
                Length        = (uint)options.PasswordLength,
                CharSet       = new PwCharSet()
            };

            if (options.UpperCasePatternSelected)
            {
                pwProfile.CharSet.Add(PwCharSet.UpperCase);
            }
            if (options.LowerCasePatternSelected)
            {
                pwProfile.CharSet.Add(PwCharSet.LowerCase);
            }
            if (options.DigitsPatternSelected)
            {
                pwProfile.CharSet.Add(PwCharSet.Digits);
            }
            if (options.SpecialPatternSelected)
            {
                pwProfile.CharSet.Add(PwCharSet.Special);
            }
            if (options.MinusPatternSelected)
            {
                pwProfile.CharSet.Add('-');
            }
            if (options.UnderscorePatternSelected)
            {
                pwProfile.CharSet.Add('_');
            }
            if (options.SpacePatternSelected)
            {
                pwProfile.CharSet.Add(' ');
            }
            if (options.BracketsPatternSelected)
            {
                pwProfile.CharSet.Add(PwCharSet.Brackets);
            }

            pwProfile.CharSet.Add(options.CustomChars);

            ProtectedString password;

            PwGenerator.Generate(out password, pwProfile, null, new CustomPwGeneratorPool());

            return(password.ReadString());
        }
        public IHttpActionResult Generate(int length, bool upperCase = false, bool digits = true, bool specialCharacters = false)
        {
            string password;

            try
            {
                password = PwGenerator.Generate(length, upperCase, digits, specialCharacters).ReadString();
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }

            return(Ok(password));
        }
Example #14
0
        private void CreateNewPassword(PwProfile prof)
        {
            if (prof == null)
            {
                prof = PwProfile.DeriveFromPassword(m_pcadata.OldPassword);
            }
            if (prof.CollectUserEntropy && (m_pbEntropy == null))
            {
                m_pbEntropy = EntropyForm.CollectEntropyIfEnabled(prof);
            }
            ProtectedString psNew;

            PwGenerator.Generate(out psNew, prof, m_pbEntropy, Program.PwGeneratorPool);
            m_icgNewPassword.SetPassword(psNew, true);
        }
Example #15
0
        private ProtectedString CreatePassword()
        {
            ProtectedString pw = new ProtectedString();
            PwProfile       pf = new PwProfile();

            pf.GeneratorType = PasswordGeneratorType.Pattern;
            //use 256bit Hex-Key-Profile
            pf.Pattern = "h{64}";
            CustomPwGeneratorPool pwGenPool = new CustomPwGeneratorPool();
            PwgError perr = PwGenerator.Generate(out pw, pf, null, pwGenPool);

            if (perr != PwgError.Success)
            {
                throw new Exception("Error while creating new password!");
            }
            return(pw);
        }
Example #16
0
        private void OnPwGenOpen(object sender, EventArgs e)
        {
            PwGeneratorForm pgf             = new PwGeneratorForm();
            ProtectedString ps              = current_password_field.TextEx;
            bool            bAtLeastOneChar = (ps.Length > 0);
            PwProfile       opt             = PwProfile.DeriveFromPassword(ps);

            pgf.InitEx(bAtLeastOneChar ? opt : null, true, false);
            if (pgf.ShowDialog() == DialogResult.OK)
            {
                byte[]          pbEntropy = EntropyForm.CollectEntropyIfEnabled(pgf.SelectedProfile);
                ProtectedString psNew;
                PwGenerator.Generate(out psNew, pgf.SelectedProfile, pbEntropy,
                                     Program.PwGeneratorPool);

                current_password_confirm_field.TextEx = current_password_field.TextEx = psNew;
            }
        }
Example #17
0
        internal JObject GeneratePassword()
        {
            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);
                var  item  = new JObject {
                    { "bits", uBits }, { "password", StrUtil.Utf8.GetString(pbNew) }
                };
                MemUtil.ZeroByteArray(pbNew);
                return(item);
            }
            return(null);
        }
Example #18
0
        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;
                        }
                    }
                }
            }

            ProtectedString ps;
            PwgError        e = PwGenerator.Generate(out ps, prf, null,
                                                     Program.PwGeneratorPool);

            if ((e != PwgError.Success) || (ps == null))
            {
                return(string.Empty);
            }

            string strGen = ps.ReadString();

            strGen = SprEngine.TransformContent(strGen, ctx);
            return(strGen);
        }
Example #19
0
        public override ProtectedString Generate(PwProfile prf, CryptoRandomStream crsRandomSource)
        {
            PwProfile p = InitProfile(prf);

            string sPattern = MapCharsets2Pattern(prf);

            p.Pattern = sPattern;
            int iLength = p.Pattern.Length;

            //Add additionaly specified characters if any
            //Increase overall length of generated password by 1: 1 per set = at least 1 out of the additinaly specified characters
            string sAdditionalChars = GetAdditionalChars(prf);

            if (AddAdditionalChars(p, sAdditionalChars))
            {
                iLength++;
            }

            //Calculate remaining length
            iLength = (int)p.Length - iLength;

            bool bSuccess;

            FinalizePattern(p, sPattern, sAdditionalChars, iLength, out bSuccess);

            if (!bSuccess)
            {
                return(ProtectedString.Empty);
            }

            ProtectedString ps = ProtectedString.Empty;

            if (PwGenerator.Generate(out ps, p, crsRandomSource.GetRandomBytes(32), null) == PwgError.Success)
            {
                return(ps);
            }
            return(ProtectedString.Empty);
        }
Example #20
0
        private static IDictionary <string, ProtectedString> OpenKeePassDB(SecureString Password)
        {
            PwDatabase       PwDB    = new PwDatabase();
            IOConnectionInfo mioInfo = new IOConnectionInfo
            {
                Path = pathToKeePassDb
            };
            CompositeKey compositeKey = new CompositeKey();

            compositeKey.AddUserKey(new KcpPassword(Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(Password))));
            IStatusLogger statusLogger = new NullStatusLogger();

            Dictionary <string, ProtectedString> dict = new Dictionary <string, ProtectedString>();

            try
            {
                PwDB.Open(mioInfo, compositeKey, statusLogger);
                PwObjectList <PwGroup> groups = PwDB.RootGroup.GetGroups(true);

                if (workingMode == WorkingModes.Prepare)
                {
                    // Check whether the requested group already exists
                    if (!groups.Any(x => x.Name.Equals(groupName)))
                    {
                        PwDB.RootGroup.AddGroup(new PwGroup()
                        {
                            Name = groupName
                        }, true);
                        Trace.TraceInformation($"The Group {groupName} has been added to KeePass DB");
                    }
                    PwGroup grp = PwDB.RootGroup.GetGroups(true).Where(x => x.Name.Equals(groupName)).First();
                    // Check if the required entry doesn't exist in the group
                    if (!grp.GetEntries(false).Any(x => x.Strings.ReadSafe("Title").Equals(entryName)))
                    {
                        //Need to have a local variable for Protected dic
                        //otherwise the clause becomes too complecated for reading
                        ProtectedStringDictionary d = new ProtectedStringDictionary();
                        d.Set("Title", new ProtectedString(true, entryName));
#pragma warning disable CS0618 // Type or member is obsolete
                        //They tell it is obsolete and recommend to use any other constructor,
                        //but, actually, there's no other to be used.
                        grp.AddEntry(new PwEntry(grp, true, true)
                        {
                            Strings = d
                        }, true);
#pragma warning restore CS0618 // Type or member is obsolete
                        Trace.TraceInformation($"The Entry {entryName} has been added to KeePass DB");
                    }
                    PwEntry ent = grp.GetEntries(false).Where(x => x.Strings.ReadSafe("Title").Equals(entryName)).First();
                    //Create a value for password
                    ProtectedString aesPwd = new ProtectedString();
                    PwGenerator.Generate(out aesPwd, new PwProfile()
                    {
                        Length  = 16,
                        CharSet = new PwCharSet(PwCharSet.LowerCase +
                                                PwCharSet.UpperCase +
                                                PwCharSet.Digits +
                                                PwCharSet.PrintableAsciiSpecial)
                    },
                                         UTF8Encoding.UTF8.GetBytes(RndString.GetRandomString(16)),
                                         new CustomPwGeneratorPool());
                    //Create a vlaue for Salt
                    ProtectedString salt = new ProtectedString();
                    PwGenerator.Generate(out salt, new PwProfile()
                    {
                        Length  = 26,
                        CharSet = new PwCharSet(PwCharSet.LowerCase +
                                                PwCharSet.UpperCase +
                                                PwCharSet.Digits +
                                                PwCharSet.PrintableAsciiSpecial)
                    },
                                         UTF8Encoding.UTF8.GetBytes(RndString.GetRandomString(28)),
                                         new CustomPwGeneratorPool());
                    ent.Strings.Set("AESpassword", new ProtectedString(true, aesPwd.ReadString()));
                    Trace.TraceInformation($"The value of the AESPass in the Entry {entryName} has been added to KeePass DB");
                    ent.Strings.Set("Salt", new ProtectedString(true, salt.ReadString()));
                    Trace.TraceInformation($"The value of the Salt in the Entry {entryName} has been added to KeePass DB");
                    // Create IV
                    SymmetricAlgorithm cipher = SymmetricAlgorithm.Create("AesManaged");
                    cipher.Mode    = CipherMode.CBC;
                    cipher.Padding = PaddingMode.PKCS7;
                    ent.Strings.Set("IV", new ProtectedString(true, Convert.ToBase64String(cipher.IV)));
                    Trace.TraceInformation($"The value of the IV in the Entry {entryName} has been added to KeePass DB");
                    PwDB.Save(statusLogger);
                    // Add dummy values to the dictionary to pass the check in the end of the method
                    dict.Add("Salt", new ProtectedString(true, ent.Strings.ReadSafe("Salt")));
                    dict.Add("Password", new ProtectedString(true, "dummy"));
                    dict.Add("AESPass", new ProtectedString(true, ent.Strings.ReadSafe("AESpassword")));
                    dict.Add("UserName", new ProtectedString(true, "dummy"));
                    dict.Add("IV", new ProtectedString(true, ent.Strings.ReadSafe("IV")));
                    dict.Add("SecurityToken", new ProtectedString(true, "dummy"));
                }
                else
                {
                    foreach (PwGroup grp in groups)
                    {
                        if (grp.Name.Equals(groupName))
                        {
                            PwObjectList <PwEntry> entries = grp.GetEntries(false);
                            foreach (PwEntry ent in entries)
                            {
                                if (ent.Strings.ReadSafe("Title").Equals(entryName))
                                {
                                    dict.Add("Salt", new ProtectedString(true, ent.Strings.ReadSafe("Salt")));
                                    dict.Add("Password", new ProtectedString(true, ent.Strings.ReadSafe("Password")));
                                    dict.Add("AESPass", new ProtectedString(true, ent.Strings.ReadSafe("AESpassword")));
                                    dict.Add("UserName", new ProtectedString(true, ent.Strings.ReadSafe("UserName")));
                                    dict.Add("IV", new ProtectedString(true, ent.Strings.ReadSafe("IV")));
                                    dict.Add("SecurityToken", new ProtectedString(true, ent.Strings.ReadSafe("SecurityToken")));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError($"Failed to open KeePassDb \n{ex.Message}");
            }
            finally
            {
                PwDB.Close();
            }
            //Delete key-value pairs where values are empty
            dict.Where(d => d.Value.IsEmpty).ToList().ForEach(t => dict.Remove(t.Key));
            return(dict);
        }
Example #21
0
        public JsonResult Generate(bool uppercase, bool numeric, bool specialchars, int length)
        {
            var result = PwGenerator.Generate(length, uppercase, numeric, specialchars).ReadString();

            return(Json(result));
        }
Example #22
0
        private void CreateEntry()
        {
            if (mCreatingEntry)
            {
                return;
            }
            mCreatingEntry = true;
            try
            {
                // Unlock, if required
                m_host.MainWindow.ProcessAppMessage((IntPtr)Program.AppMessage.Unlock, IntPtr.Zero);

                if (m_host.MainWindow.IsAtLeastOneFileOpen())
                {
                    string selectedText, url, title;
                    WebBrowserUrl.GetFocusedBrowserInfo(mChromeAccessibility, out selectedText, out url, out title);

                    var urlSuggestions = new List <String>();
                    if (!String.IsNullOrEmpty(url))
                    {
                        // Use only the root part of the URL
                        try
                        {
                            var uri = new Uri(url);
                            urlSuggestions.Add(uri.GetLeftPart(UriPartial.Authority) + "/");
                            urlSuggestions.Add(uri.GetLeftPart(UriPartial.Path));
                            urlSuggestions.Add(uri.GetLeftPart(UriPartial.Query));
                        }
                        catch (UriFormatException)
                        {
                        }
                        // Finally, the url exactly as given
                        urlSuggestions.Add(url);
                    }

                    // Logic adapted from EntryTemplates.CreateEntry
                    var database = m_host.Database;
                    var entry    = new PwEntry(true, true);
                    if (!String.IsNullOrEmpty(title))
                    {
                        entry.Strings.Set(PwDefs.TitleField, new ProtectedString(database.MemoryProtection.ProtectTitle, title));
                    }
                    if (urlSuggestions.Any())
                    {
                        entry.Strings.Set(PwDefs.UrlField, new ProtectedString(database.MemoryProtection.ProtectUrl, urlSuggestions[0]));
                    }
                    if (!String.IsNullOrEmpty(selectedText))
                    {
                        entry.Strings.Set(PwDefs.UserNameField, new ProtectedString(database.MemoryProtection.ProtectUserName, selectedText));
                    }

                    // Generate a default password, the same as in MainForm.OnEntryAdd
                    ProtectedString psAutoGen;
                    PwGenerator.Generate(out psAutoGen, Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile, null, Program.PwGeneratorPool);
                    psAutoGen = psAutoGen.WithProtection(database.MemoryProtection.ProtectPassword);
                    entry.Strings.Set(PwDefs.PasswordField, psAutoGen);


                    PwGroup group = database.RootGroup;
                    if (CreateEntryTargetGroup != null)
                    {
                        group = database.RootGroup.FindGroup(CreateEntryTargetGroup, true) ?? database.RootGroup;
                    }

                    // Set parent group temporarily, so that the AutoType tab, and other plugins such as PEDCalc, can obtain it in the PwEntryForm.
                    //entry.ParentGroup = group;
                    var parentGroupProperty = typeof(PwEntry).GetProperty("ParentGroup", BindingFlags.Instance | BindingFlags.Public);
                    if (parentGroupProperty != null)
                    {
                        parentGroupProperty.SetValue(entry, @group);
                    }

                    using (var entryForm = new PwEntryForm())
                    {
                        entryForm.InitEx(entry, PwEditMode.AddNewEntry, database, m_host.MainWindow.ClientIcons, false, true);

                        // Customise entry form to show drop-down for selecting URL
                        var urlBox = entryForm.Controls.Find("m_tbUrl", true).FirstOrDefault();
                        if (urlBox != null)
                        {
                            var urlCombo = new ComboBox
                            {
                                DropDownStyle = ComboBoxStyle.DropDown,
                                TabIndex      = urlBox.TabIndex,
                                Text          = urlBox.Text,
                            };
                            foreach (var urlSuggestion in urlSuggestions.Distinct())
                            {
                                urlCombo.Items.Add(urlSuggestion);
                            }
                            var syncPos = new EventHandler(delegate { urlCombo.SetBounds(urlBox.Left, urlBox.Top, urlBox.Width, urlBox.Height); });
                            urlBox.Resize += syncPos;
                            syncPos(null, EventArgs.Empty);                             // Initial sizing
                            urlBox.Parent.Controls.Add(urlCombo);
                            urlBox.Visible = false;

                            // Sync text
                            urlCombo.TextChanged += delegate { urlBox.Text = urlCombo.Text; };
                            urlBox.TextChanged   += delegate { urlCombo.Text = urlBox.Text; };
                        }

                        if (ShowForegroundDialog(entryForm) == DialogResult.OK)
                        {
                            group.AddEntry(entry, true, true);
                            m_host.MainWindow.UpdateUI(false, null, database.UINeedsIconUpdate, null, true, null, true);
                        }
                        else
                        {
                            m_host.MainWindow.UpdateUI(false, null, database.UINeedsIconUpdate, null, database.UINeedsIconUpdate, null, false);
                        }
                    }
                }
            }
            finally
            {
                mCreatingEntry = false;
            }
        }
Example #23
0
        internal static ProtectedString GenerateAcceptable(PwProfile prf,
                                                           byte[] pbUserEntropy, PwEntry peOptCtx, PwDatabase pdOptCtx,
                                                           bool bShowErrorUI, ref bool bAcceptAlways, out string strError)
        {
            strError = null;

            ProtectedString ps  = ProtectedString.Empty;
            SprContext      ctx = new SprContext(peOptCtx, pdOptCtx,
                                                 SprCompileFlags.NonActive, false, false);

            while (true)
            {
                try
                {
                    PwgError e = PwGenerator.Generate(out ps, prf, pbUserEntropy,
                                                      Program.PwGeneratorPool);

                    if (e != PwgError.Success)
                    {
                        strError = PwGenerator.ErrorToString(e, true);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    strError = PwGenerator.ErrorToString(ex, true);
                    break;
                }
                finally
                {
                    if (ps == null)
                    {
                        Debug.Assert(false); ps = ProtectedString.Empty;
                    }
                }

                if (bAcceptAlways)
                {
                    break;
                }

                string str    = ps.ReadString();
                string strCmp = SprEngine.Compile(str, ctx);

                if (str != strCmp)
                {
                    if (prf.GeneratorType == PasswordGeneratorType.CharSet)
                    {
                        continue;                         // Silently try again
                    }
                    string strText = str + MessageService.NewParagraph +
                                     KPRes.GenPwSprVariant + MessageService.NewParagraph +
                                     KPRes.GenPwAccept;

                    if (!MessageService.AskYesNo(strText, null, false))
                    {
                        continue;
                    }
                    bAcceptAlways = true;
                }

                break;
            }

            if (!string.IsNullOrEmpty(strError))
            {
                ps = ProtectedString.Empty;
                if (bShowErrorUI)
                {
                    MessageService.ShowWarning(strError);
                }
            }

            return(ps);
        }
Example #24
0
 void WhenIGenerateANewDefaultPassword()
 {
     password = PwGenerator.Generate(passwordLength).ReadString();
 }
Example #25
0
 void WhenWeGenerateANewPasswordWithUpperCaseCharacters()
 {
     password = PwGenerator.Generate(passwordLength, true).ReadString();
 }
Example #26
0
 void WhenWeGenerateAPasswordWithUpperAndDigitCharacters()
 {
     password = PwGenerator.Generate(passwordLength, true, true).ReadString();
 }