Ejemplo n.º 1
0
        public static PSObject CreateEntryResult(PwDatabase db, PwEntry passwordEntry, bool asUnprotectedStrings, bool resolveReferencedFields)
        {
            var result = new PSObject();

            result.AddProperty("Id", passwordEntry.Uuid.ToHexString());
            result.AddProperty("GroupName", passwordEntry.ParentGroup.Name);
            result.AddProperty("Path", passwordEntry.CreateGroupPath());
            result.AddPropertyIfNotNullOrEmpty(PwDefs.TitleField, GetStringEntry(PwDefs.TitleField, db, passwordEntry, asUnprotectedStrings, resolveReferencedFields));
            result.AddPropertyIfNotNullOrEmpty(PwDefs.UserNameField, GetStringEntry(PwDefs.UserNameField, db, passwordEntry, asUnprotectedStrings, resolveReferencedFields));
            result.AddProperty(PwDefs.PasswordField, asUnprotectedStrings ? (object)passwordEntry.Strings.Get(PwDefs.PasswordField).ReadString() : passwordEntry.Strings.Get(PwDefs.PasswordField).ReadUtf8().ToSecureString(Encoding.UTF8));
            result.AddProperty("EstimatedPasswordQualityBits", QualityEstimation.EstimatePasswordBits(passwordEntry.Strings.Get(PwDefs.PasswordField).ReadUtf8()));

            if (passwordEntry.Tags != null && passwordEntry.Tags.Any())
            {
                result.AddProperty("Tags", passwordEntry.Tags);
            }

            result.AddProperty("Expires", passwordEntry.Expires);
            if (passwordEntry.Expires)
            {
                result.AddProperty("IsExpired", passwordEntry.ExpiryTime < DateTime.Now);
                result.AddProperty("ExpireTime", passwordEntry.ExpiryTime);
            }

            foreach (var key1 in passwordEntry.Strings.GetKeys().Where(x => !new[] { PwDefs.TitleField, PwDefs.PasswordField, PwDefs.UserNameField }.Contains(x)))
            {
                result.AddPropertyIfNotNullOrEmpty(key1, GetStringEntry(key1, db, passwordEntry, asUnprotectedStrings, resolveReferencedFields));
            }
            // Version 2.36
            //foreach (var key1 in passwordEntry.CustomData)
            //{
            //    result.AddPropertyIfNotNullOrEmpty(key1.Key, key1.Value);
            //}
            return(result);
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        private static void EstimateQuality(CommandLineArgs args)
        {
            string str = args[ParamText];

            if (string.IsNullOrEmpty(str))
            {
                Console.WriteLine("0");
                return;
            }

            try
            {
                ResourceManager rm     = KeePass.Program.Resources;
                byte[]          pbData = (byte[])rm.GetObject("MostPopularPasswords");
                if (pbData != null)
                {
                    PopularPasswords.Add(pbData, true);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
            catch (Exception) { Debug.Assert(false); return; }

            uint uBits = QualityEstimation.EstimatePasswordBits(
                str.ToCharArray());

            Console.WriteLine(uBits);
        }
Ejemplo n.º 4
0
        public override string GetCellData(string strColumnName, PwEntry pe)
        {
            if (strColumnName == null)
            {
                Debug.Assert(false); return(string.Empty);
            }
            if (strColumnName != Globals.COLUMN_NAME)
            {
                return(string.Empty);
            }
            if (pe == null)
            {
                Debug.Assert(false); return(string.Empty);
            }

            string strPw = pe.Strings.ReadSafe(PwDefs.PasswordField);

            if (strPw.IndexOf('{') >= 0)
            {
                IPluginHost host = ColoredQualityColumnExt.Host;
                if (host == null)
                {
                    Debug.Assert(false); return(string.Empty);
                }

                PwDatabase pd = null;
                try
                {
                    pd = host.MainWindow.DocumentManager.SafeFindContainerOf(pe);
                }
                catch (Exception) { Debug.Assert(false); }

                SprContext ctx = new SprContext(pe, pd, (SprCompileFlags.Deref |
                                                         SprCompileFlags.TextTransforms), false, false);
                strPw = SprEngine.Compile(strPw, ctx);
            }

            uint uEst;

            lock (m_oCacheSync)
            {
                if (!m_dCache.TryGetValue(strPw, out uEst))
                {
                    uEst = uint.MaxValue;
                }
            }

            if (uEst == uint.MaxValue)
            {
                uEst = QualityEstimation.EstimatePasswordBits(strPw.ToCharArray());

                lock (m_oCacheSync)
                {
                    // Store quality estimation in cache.
                    m_dCache[strPw] = uEst;
                }
            }

            return(uEst.ToString() + " bits");
        }
Ejemplo n.º 5
0
        private static string ValidateNewMasterPassword(byte[] pbUtf8, uint cChars)
        {
            if (pbUtf8 == null)
            {
                Debug.Assert(false); throw new ArgumentNullException("pbUtf8");
            }

#if DEBUG
            char[] vChars = StrUtil.Utf8.GetChars(pbUtf8);
            Debug.Assert(vChars.Length == (int)cChars);
            MemUtil.ZeroArray <char>(vChars);
#endif

            uint cBits = QualityEstimation.EstimatePasswordBits(pbUtf8);

            uint cMinChars = Program.Config.Security.MasterPassword.MinimumLength;
            if (cChars < cMinChars)
            {
                return(KPRes.MasterPasswordMinLengthFailed.Replace(@"{PARAM}",
                                                                   cMinChars.ToString()));
            }

            uint cMinBits = Program.Config.Security.MasterPassword.MinimumQuality;
            if (cBits < cMinBits)
            {
                return(KPRes.MasterPasswordMinQualityFailed.Replace(@"{PARAM}",
                                                                    cMinBits.ToString()));
            }

            string strError = Program.KeyValidatorPool.Validate(pbUtf8,
                                                                KeyValidationType.MasterPassword);
            if (strError != null)
            {
                return(strError);
            }

            if (cChars == 0)
            {
                if (!MessageService.AskYesNo(KPRes.EmptyMasterPw +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwHint +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion,
                                             null, false))
                {
                    return(string.Empty);
                }
            }

            if (cBits <= PwDefs.QualityBitsWeak)
            {
                string str = KPRes.MasterPasswordWeak + MessageService.NewParagraph +
                             KPRes.MasterPasswordConfirm;
                if (!MessageService.AskYesNo(str, null, false, MessageBoxIcon.Warning))
                {
                    return(string.Empty);
                }
            }

            return(null);
        }
Ejemplo n.º 6
0
        private bool CreateCompositeKey()
        {
            m_pKey = new CompositeKey();

            if (m_secPassword.ContentsEqualTo(m_secRepeat) == false)
            {
                MessageService.ShowWarning(KPRes.PasswordRepeatFailed);
                return(false);
            }

            if (m_secPassword.TextLength == 0)
            {
                if (!MessageService.AskYesNo(KPRes.EmptyMasterPw +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwHint +
                                             MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion,
                                             null, false))
                {
                    return(false);
                }
            }

            uint uMinLen = Program.Config.Security.MasterPassword.MinimumLength;

            if (m_secPassword.TextLength < uMinLen)
            {
                string strML = KPRes.MasterPasswordMinLengthFailed;
                strML = strML.Replace(@"{PARAM}", uMinLen.ToString());
                MessageService.ShowWarning(strML);
                return(false);
            }

            byte[] pb = m_secPassword.ToUtf8();

            uint uMinQual = Program.Config.Security.MasterPassword.MinimumQuality;

            if (QualityEstimation.EstimatePasswordBits(pb) < uMinQual)
            {
                string strMQ = KPRes.MasterPasswordMinQualityFailed;
                strMQ = strMQ.Replace(@"{PARAM}", uMinQual.ToString());
                MessageService.ShowWarning(strMQ);
                Array.Clear(pb, 0, pb.Length);
                return(false);
            }

            string strValRes = Program.KeyValidatorPool.Validate(pb,
                                                                 KeyValidationType.MasterPassword);

            if (strValRes != null)
            {
                MessageService.ShowWarning(strValRes);
                Array.Clear(pb, 0, pb.Length);
                return(false);
            }

            m_pKey.AddUserKey(new KcpPassword(pb));
            Array.Clear(pb, 0, pb.Length);

            return(true);
        }
Ejemplo n.º 7
0
        private void Lv_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            if (_highlightsOn)
            {
                ListViewItem lvi = e.Item;
                PwListItem   li  = (lvi.Tag as PwListItem);
                if (li == null)
                {
                    Debug.Assert(false); return;
                }

                PwEntry pe = li.Entry;
                if (pe == null)
                {
                    Debug.Assert(false); return;
                }

                ProtectedString pStr = pe.Strings.Get(PwDefs.PasswordField);
                if (pStr == null)
                {
                    Debug.Assert(false); return;
                }

                string pw = pStr.ReadString();

                if (pw.IndexOf('{') >= 0)
                {
                    //It is a reference to another entry.
                    PwDatabase pd = null;
                    try
                    {
                        pd = _host.MainWindow.DocumentManager.SafeFindContainerOf(pe);
                    }
                    catch (Exception) { Debug.Assert(false); }

                    SprContext context = new SprContext(pe, pd, (SprCompileFlags.Deref | SprCompileFlags.TextTransforms), false, false);
                    pw = SprEngine.Compile(pw, context);
                }

                uint bits = QualityEstimation.EstimatePasswordBits(pw.ToCharArray());
                foreach (KeyValuePair <uint, Color> kvp in QualityDelimiter)
                {
                    if (bits <= kvp.Key)
                    {
                        lvi.BackColor = kvp.Value;
                        break;
                    }
                }
            }

            e.DrawDefault = true;
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
0
        private void UpdateQualityInfoTh(object oPassword)
        {
            string str = (oPassword as string);

            if (str == null)
            {
                Debug.Assert(false); return;
            }

            try
            {
                Debug.Assert(m_tbPassword.InvokeRequired);
                // byte[] pbUtf8 = (m_tbPassword.Invoke(new UqiGetPasswordFn(
                //	this.UqiGetPassword)) as byte[]);
                // if(pbUtf8 == null) { Debug.Assert(false); return; }
                byte[] pbUtf8 = StrUtil.Utf8.GetBytes(str);

                // str = StrUtil.Utf8.GetString(pbUtf8);
                // lock(m_lUqiTasks) { m_lUqiTasks.Add(str); }

                uint uBits = QualityEstimation.EstimatePasswordBits(pbUtf8);

                TextBox tb = m_tbPassword;
                if (tb == null)
                {
                    return;                            // Control disposed in the meanwhile
                }
                byte[] pbNewUtf8 = (tb.Invoke(new UqiGetPasswordDelegate(
                                                  this.UqiGetPassword)) as byte[]);
                if (pbNewUtf8 == null)
                {
                    Debug.Assert(false); return;
                }

                // Test whether password has changed in the meanwhile
                if (!MemUtil.ArraysEqual(pbUtf8, pbNewUtf8))
                {
                    return;
                }

                tb.Invoke(new UqiShowQualityDelegate(this.UqiShowQuality),
                          uBits, (uint)str.Length);
            }
            catch (Exception) { Debug.Assert(false); }
            finally
            {
                lock (m_lUqiTasks) { m_lUqiTasks.Remove(str); }
            }
        }
        public IHttpActionResult Validate(string password)
        {
            var validationResult = 0;

            try
            {
                validationResult = (int)QualityEstimation.EstimatePasswordBits(password.ToCharArray());
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }

            return(Ok(validationResult));
        }
        private void UpdateQualityInfoTh(object oPassword)
        {
            char[] v = (oPassword as char[]);
            if (v == null)
            {
                Debug.Assert(false); return;
            }

            char[] vNew = null;
            try
            {
                Debug.Assert(m_tbPassword.InvokeRequired);

                uint uBits = QualityEstimation.EstimatePasswordBits(v);

                SecureTextBoxEx tb = m_tbPassword;
                if (tb == null)
                {
                    return;                            // Control disposed in the meanwhile
                }
                // Test whether the password has changed in the meanwhile
                vNew = (tb.Invoke(new UqiGetPasswordDelegate(
                                      this.UqiGetPassword)) as char[]);
                if (!MemUtil.ArrayHelperExOfChar.Equals(v, vNew))
                {
                    return;
                }

                tb.Invoke(new UqiShowQualityDelegate(this.UqiShowQuality),
                          uBits, (uint)v.Length);
            }
            catch (Exception) { Debug.Assert(false); }
            finally
            {
                string strTask = GetUqiTaskID(v);
                lock (m_oUqiTasksSync) { m_lUqiTasks.Remove(strTask); }

                MemUtil.ZeroArray <char>(v);
                if (vNew != null)
                {
                    MemUtil.ZeroArray <char>(vNew);
                }
            }
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
0
        private void ProcessTextChangedPassword(object sender, EventArgs e)
        {
            byte[] pbUTF8 = m_secPassword.ToUtf8();
            uint   uBits  = QualityEstimation.EstimatePasswordBits(pbUTF8);

            MemUtil.ZeroByteArray(pbUTF8);

            m_lblQualityBits.Text = uBits.ToString() + " " + KPRes.Bits;
            int iPos = (int)((100 * uBits) / (256 / 2));

            if (iPos < 0)
            {
                iPos = 0;
            }
            else if (iPos > 100)
            {
                iPos = 100;
            }
            m_pbPasswordQuality.Value = iPos;
        }
Ejemplo n.º 14
0
        /// <inheritdoc/>
        public override ProtectedString Generate(CryptoRandomStream random, Settings settings)
        {
            if (random == null)
            {
                throw new ArgumentNullException("random" /*nameof(random)*/);
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings" /*nameof(settings)*/);
            }

            var wordlist = GetWordlist(settings);
            var result   = new List <string>();

            do
            {
                result.Add(wordlist[random.Next(0, wordlist.Length)]);
            }while (QualityEstimation.EstimatePasswordBits(string.Join(string.Empty, result.ToArray()).ToCharArray()) < Count);
            return(new ProtectedString(true, string.Join(Separator, result.ToArray())));
        }
 void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
 {
     if (passwordEntry.Text.Equals(confirmEntry.Text) && !string.IsNullOrEmpty(passwordEntry.Text) && !string.IsNullOrEmpty(confirmEntry.Text))
     {
         uint result = QualityEstimation.EstimatePasswordBits(passwordEntry.Text.ToCharArray());
         if (result < 50)
         {
             strengthLabel.Text = Config.NotStrongPassword;
             markImage.Source   = "unhappy.png";
         }
         else
         {
             strengthLabel.Text = "";
             markImage.Source   = "tick.png";
         }
     }
     else
     {
         strengthLabel.Text = "";
         markImage.Source   = "";
     }
 }
Ejemplo n.º 16
0
        private bool CreateCompositeKey()
        {
            m_pKey = new CompositeKey();

            if (m_cbPassword.Checked)            // Use a password
            {
                if (!m_icgPassword.ValidateData(true))
                {
                    return(false);
                }

                uint uPwLen = m_icgPassword.PasswordLength;
                if (uPwLen == 0)
                {
                    if (!MessageService.AskYesNo(KPRes.EmptyMasterPw +
                                                 MessageService.NewParagraph + KPRes.EmptyMasterPwHint +
                                                 MessageService.NewParagraph + KPRes.EmptyMasterPwQuestion,
                                                 null, false))
                    {
                        return(false);
                    }
                }

                uint uMinLen = Program.Config.Security.MasterPassword.MinimumLength;
                if (uPwLen < uMinLen)
                {
                    string strML = KPRes.MasterPasswordMinLengthFailed;
                    strML = strML.Replace(@"{PARAM}", uMinLen.ToString());
                    MessageService.ShowWarning(strML);
                    return(false);
                }

                byte[] pb = m_icgPassword.GetPasswordUtf8();

                uint uMinQual = Program.Config.Security.MasterPassword.MinimumQuality;
                if (QualityEstimation.EstimatePasswordBits(pb) < uMinQual)
                {
                    string strMQ = KPRes.MasterPasswordMinQualityFailed;
                    strMQ = strMQ.Replace(@"{PARAM}", uMinQual.ToString());
                    MessageService.ShowWarning(strMQ);
                    MemUtil.ZeroByteArray(pb);
                    return(false);
                }

                string strValRes = Program.KeyValidatorPool.Validate(pb,
                                                                     KeyValidationType.MasterPassword);
                if (strValRes != null)
                {
                    MessageService.ShowWarning(strValRes);
                    MemUtil.ZeroByteArray(pb);
                    return(false);
                }

                m_pKey.AddUserKey(new KcpPassword(pb));
                MemUtil.ZeroByteArray(pb);
            }

            string strKeyFile = m_cmbKeyFile.Text;
            bool   bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(strKeyFile);

            if (m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) &&
                !bIsKeyProv)
            {
                try { m_pKey.AddUserKey(new KcpKeyFile(strKeyFile, true)); }
                catch (InvalidDataException exID)                // Selected database file
                {
                    MessageService.ShowWarning(strKeyFile, exID);
                    return(false);
                }
                catch (Exception exKF)
                {
                    MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKF);
                    return(false);
                }
            }
            else if (m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) &&
                     bIsKeyProv)
            {
                KeyProviderQueryContext ctxKP = new KeyProviderQueryContext(
                    m_ioInfo, true, false);

                bool   bPerformHash;
                byte[] pbCustomKey = Program.KeyProviderPool.GetKey(strKeyFile, ctxKP,
                                                                    out bPerformHash);
                if ((pbCustomKey != null) && (pbCustomKey.Length > 0))
                {
                    try { m_pKey.AddUserKey(new KcpCustomKey(strKeyFile, pbCustomKey, bPerformHash)); }
                    catch (Exception exCKP)
                    {
                        MessageService.ShowWarning(exCKP);
                        return(false);
                    }

                    MemUtil.ZeroByteArray(pbCustomKey);
                }
                else
                {
                    return(false);                 // Provider has shown error message
                }
            }

            if (m_cbUserAccount.Checked)
            {
                try { m_pKey.AddUserKey(new KcpUserAccount()); }
                catch (Exception exUA)
                {
                    MessageService.ShowWarning(exUA);
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 17
0
        private void UpdateUI()
        {
            if ((m_uBlockUIUpdate > 0) || m_bInitializing)
            {
                return;
            }
            ++m_uBlockUIUpdate;

            ulong uFlags = 0;

            if (m_fParent is KeyCreationForm)
            {
                uFlags = Program.Config.UI.KeyCreationFlags;
            }

            byte[] pbUtf8 = m_secPassword.ToUtf8();

            m_tbPassword.Enabled = m_bEnabled;
            m_cbHide.Enabled     = (m_bEnabled && ((uFlags &
                                                    (ulong)AceKeyUIFlags.DisableHidePassword) == 0));

            if ((uFlags & (ulong)AceKeyUIFlags.CheckHidePassword) != 0)
            {
                m_bPrgmCheck     = true;
                m_cbHide.Checked = true;
                m_bPrgmCheck     = false;
            }
            if ((uFlags & (ulong)AceKeyUIFlags.UncheckHidePassword) != 0)
            {
                m_bPrgmCheck     = true;
                m_cbHide.Checked = false;
                m_bPrgmCheck     = false;
            }

            bool bAutoRepeat = this.AutoRepeat;

            if (bAutoRepeat && (m_secRepeat.TextLength > 0))
            {
                m_secRepeat.SetPassword(new byte[0]);
            }

            byte[] pbRepeat = m_secRepeat.ToUtf8();
            if (!MemUtil.ArraysEqual(pbUtf8, pbRepeat) && !bAutoRepeat)
            {
                m_tbRepeat.BackColor = AppDefs.ColorEditError;
            }
            else
            {
                m_tbRepeat.ResetBackColor();
            }

            bool bRepeatEnable = (m_bEnabled && !bAutoRepeat);

            m_lblRepeat.Enabled = bRepeatEnable;
            m_tbRepeat.Enabled  = bRepeatEnable;

            m_lblQualityPrompt.Enabled = m_bEnabled;
            m_pbQuality.Enabled        = m_bEnabled;
            m_lblQualityBits.Enabled   = m_bEnabled;

            uint uBits = QualityEstimation.EstimatePasswordBits(pbUtf8);

            m_lblQualityBits.Text = uBits.ToString() + " " + KPRes.Bits;
            int iPos = (int)((100 * uBits) / (256 / 2));

            if (iPos < 0)
            {
                iPos = 0;
            }
            else if (iPos > 100)
            {
                iPos = 100;
            }
            m_pbQuality.Value = iPos;

            MemUtil.ZeroByteArray(pbUtf8);
            MemUtil.ZeroByteArray(pbRepeat);
            --m_uBlockUIUpdate;
        }
Ejemplo n.º 18
0
        private static List <KeyValuePair <PwEntry, ulong> > CreatePwQualityListEx(
            PwDatabase pd, IStatusLogger sl)
        {
            if ((pd == null) || !pd.IsOpen)
            {
                Debug.Assert(false); return(null);
            }
            PwGroup pg = pd.RootGroup;

            if (pg == null)
            {
                Debug.Assert(false); return(null);
            }

            uint uEntries     = pg.GetEntriesCount(true);
            uint uEntriesDone = 0;
            List <KeyValuePair <PwEntry, ulong> > l = new List <KeyValuePair <PwEntry, ulong> >();

            EntryHandler eh = delegate(PwEntry pe)
            {
                if ((sl != null) && (uEntries != 0))
                {
                    uint u = (uEntriesDone * 100) / uEntries;
                    if (!sl.SetProgress(u))
                    {
                        return(false);
                    }
                }
                ++uEntriesDone;                 // Also used for sorting, see below

                if (!pe.GetSearchingEnabled())
                {
                    return(true);
                }

                SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive);
                string     str = SprEngine.Compile(pe.Strings.ReadSafe(
                                                       PwDefs.PasswordField), ctx);
                if (str.Length != 0)
                {
                    uint q = QualityEstimation.EstimatePasswordBits(str.ToCharArray());
                    l.Add(new KeyValuePair <PwEntry, ulong>(pe,
                                                            ((ulong)q << 32) | (ulong)uEntriesDone));
                }

                return(true);
            };

            if (!pg.TraverseTree(TraversalMethod.PreOrder, null, eh))
            {
                return(null);
            }

            Comparison <KeyValuePair <PwEntry, ulong> > fCompare = delegate(
                KeyValuePair <PwEntry, ulong> x, KeyValuePair <PwEntry, ulong> y)
            {
                return(x.Value.CompareTo(y.Value));
            };

            l.Sort(fCompare);

            return(l);
        }
 public int EstimatePasswordComplexity(string password)
 {
     return((int)QualityEstimation.EstimatePasswordBits(password?.ToCharArray()));
 }
Ejemplo n.º 20
0
        public JsonResult Validate(string password)
        {
            var result = QualityEstimation.EstimatePasswordBits(password.ToCharArray()).ToString();

            return(Json(result));
        }
Ejemplo n.º 21
0
        private bool CreateCompositeKey()
        {
            m_pKey = new CompositeKey();

            if (m_cbPassword.Checked)            // Use a password
            {
                if (m_cbHidePassword.Checked)
                {
                    if (m_secPassword.ContentsEqualTo(m_secRepeat) == false)
                    {
                        MessageService.ShowWarning(KPRes.PasswordRepeatFailed);
                        return(false);
                    }
                }

                uint uMinLen = Program.Config.Security.MasterPassword.MinimumLength;
                if (m_secPassword.TextLength < uMinLen)
                {
                    string strML = KPRes.MasterPasswordMinLengthFailed;
                    strML = strML.Replace(@"{PARAM}", uMinLen.ToString());
                    MessageService.ShowWarning(strML);
                    return(false);
                }

                byte[] pb = m_secPassword.ToUtf8();

                uint uMinQual = Program.Config.Security.MasterPassword.MinimumQuality;
                if (QualityEstimation.EstimatePasswordBits(pb) < uMinQual)
                {
                    string strMQ = KPRes.MasterPasswordMinQualityFailed;
                    strMQ = strMQ.Replace(@"{PARAM}", uMinQual.ToString());
                    MessageService.ShowWarning(strMQ);
                    Array.Clear(pb, 0, pb.Length);
                    return(false);
                }

                m_pKey.AddUserKey(new KcpPassword(pb));
                Array.Clear(pb, 0, pb.Length);
            }

            string strKeyFile = m_cmbKeyFile.Text;
            bool   bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(strKeyFile);

            if (m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) &&
                (bIsKeyProv == false))
            {
                try { m_pKey.AddUserKey(new KcpKeyFile(strKeyFile)); }
                catch (Exception exKF)
                {
                    MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKF);
                    return(false);
                }
            }
            else if (m_cbKeyFile.Checked && (!strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) &&
                     (bIsKeyProv == true))
            {
                byte[] pbCustomKey = Program.KeyProviderPool.GetKey(strKeyFile);

                try { m_pKey.AddUserKey(new KcpCustomKey(pbCustomKey)); }
                catch (Exception exCKP)
                {
                    MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exCKP);
                    return(false);
                }

                if ((pbCustomKey != null) && (pbCustomKey.Length > 0))
                {
                    Array.Clear(pbCustomKey, 0, pbCustomKey.Length);
                }
            }

            if (m_cbUserAccount.Checked)
            {
                try { m_pKey.AddUserKey(new KcpUserAccount()); }
                catch (Exception exUA)
                {
                    MessageService.ShowWarning(exUA);
                    return(false);
                }
            }

            return(true);
        }
 private void textNewPassword_TextChanged(object sender, System.EventArgs args)
 {
     this.qualityProgressBar.Value = (int)QualityEstimation.EstimatePasswordQuality(this.textNewPassword.Text);
 }
 void WhenICalculatePasswordQuality()
 {
     qualityResult = QualityEstimation.EstimatePasswordBits(testPassword.ToCharArray());
 }
        private void buttonOK_Click(object sender, System.EventArgs args)
        {
            var tmpCreateResult      = false;
            var tmpInputErrorCaption = SafePassResource.MessageBoxCaptionInputError;

            var tmpLoginName = this.textLoginName.Text.Trim();

            if (string.IsNullOrEmpty(tmpLoginName))
            {
                this.textLoginName.Focus();
                MessageBox.Show(SafePassResource.NewWizardWindowPromptLoginNameIsEmpty, tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (tmpLoginName.Length > 30)
            {
                this.textLoginName.Focus();
                MessageBox.Show(SafePassResource.NewWizardWindowPromptLoginNameTooLong, tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var tmpPassword       = this.textPassword.Text.Trim();
            var tmpMasterPassword = Program.Config.Application.Security.MasterPassword;

            if (string.IsNullOrEmpty(tmpPassword))
            {
                this.textPassword.Focus();
                MessageBox.Show(SafePassResource.NewWizardWindowPromptPasswordIsEmpty, tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (tmpPassword.Length < tmpMasterPassword.MinimumLength)
            {
                this.textPassword.Focus();
                MessageBox.Show(string.Format(SafePassResource.MasterPasswordMinimumLengthFailed, tmpMasterPassword.MinimumLength), tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (QualityEstimation.EstimatePasswordQuality(tmpPassword) < tmpMasterPassword.MinimumQuality)
            {
                this.textPassword.Focus();
                MessageBox.Show(string.Format(SafePassResource.MasterPasswordMinimumQualityFailed, tmpMasterPassword.MinimumQuality), tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (!string.Equals(tmpPassword, this.textPwdRepeat.Text))
            {
                this.textPwdRepeat.Focus();
                MessageBox.Show(SafePassResource.PasswordRepeatFailed, tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var tmpSafePassName = this.textSafePassName.Text.Trim();

            if (string.IsNullOrEmpty(tmpSafePassName))
            {
                this.textSafePassName.Focus();
                MessageBox.Show(SafePassResource.NewWizardWindowPromptSafePassNameIsEmpty, tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (StringHelper.GetStringBytesCount(tmpSafePassName) > 30)
            {
                this.textSafePassName.Focus();
                MessageBox.Show(SafePassResource.NewWizardWindowPromptSafePassNameTooLong, tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var tmpRootDirectory = new DirectoryInfo(this.textWorkDirectory.Text);

            if (!tmpRootDirectory.Exists)
            {
                tmpRootDirectory = Directory.CreateDirectory(this.textWorkDirectory.Text);
            }

            DirectoryInfo tmpWorkDirectory;

            if (string.Equals(tmpRootDirectory.Name, tmpLoginName, System.StringComparison.OrdinalIgnoreCase))
            {
                tmpWorkDirectory = new DirectoryInfo(tmpRootDirectory.FullName);
            }
            else
            {
                tmpWorkDirectory = new DirectoryInfo(Path.Combine(tmpRootDirectory.FullName, tmpLoginName));
                if (!tmpWorkDirectory.Exists)
                {
                    tmpWorkDirectory = Directory.CreateDirectory(tmpWorkDirectory.FullName);
                }
            }


            if (tmpWorkDirectory.Exists)
            {
                var files = tmpWorkDirectory.GetFiles("*.*", SearchOption.AllDirectories);
                if (files != null && files.Length > 0)
                {
                    MessageBox.Show(string.Format(SafePassResource.NewWizardWindowWorkDirectoryNotEmpty, tmpWorkDirectory.FullName), tmpInputErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                NativeShellHelper.SetWorkingDirectory(tmpWorkDirectory.FullName);
                var tmpDataDirectory = Path.Combine(tmpWorkDirectory.FullName, "data");

                if (!Directory.Exists(tmpDataDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(tmpDataDirectory);
                    }
                    catch (System.SystemException exception)
                    {
                        loger.Error(exception);
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                    }
                }

                var tmpConfigDirectory = Path.Combine(tmpWorkDirectory.FullName, "config");
                if (!Directory.Exists(tmpConfigDirectory))
                {
                    try
                    {
                        Directory.CreateDirectory(tmpConfigDirectory);
                    }
                    catch (System.SystemException exception)
                    {
                        loger.Error(exception);
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                    }
                }

                if (Directory.Exists(tmpConfigDirectory))
                {
                    try
                    {
                        //this.CreateLog4NetConfig( );
                        this.CreateApplicationConfig(tmpConfigDirectory, tmpLoginName, tmpPassword);
                    }
                    catch (System.SystemException exception)
                    {
                        loger.Error(exception);
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                    }
                }

                if (Directory.Exists(tmpDataDirectory))
                {
                    try
                    {
                        tmpCreateResult = this.InitializeDataBase(tmpDataDirectory, tmpLoginName, tmpPassword);
                    }
                    catch (System.SystemException exception)
                    {
                        loger.Error(exception);
                        System.Diagnostics.Debug.WriteLine(exception.Message);
                    }
                }
            }

            if (tmpCreateResult)
            {
                MessageBox.Show(SafePassResource.NewWizardWindowDialogMessageCreateSuccess, SafePassResource.NewWizardWindowDialogTitleCreateSuccess, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
            }
        }