コード例 #1
0
 public static void ShowSaveWarning(IOConnectionInfo ioConnection, Exception ex,
                                    bool bCorruptionWarning)
 {
     if (ioConnection != null)
     {
         ShowSaveWarning(ioConnection.GetDisplayName(), ex, bCorruptionWarning);
     }
     else
     {
         ShowWarning(ex);
     }
 }
コード例 #2
0
        private static bool CreateAuxFile(Info Info,
                                          KeyProviderQueryContext ctx)
        {
            IOConnectionInfo ioc = GetAuxFileIoc(ctx);

            if (!Info.Save(ioc, Info))
            {
                MessageService.ShowWarning("Failed to save auxiliary OTP info file:",
                                           ioc.GetDisplayName());
                return(false);
            }
            return(true);
        }
コード例 #3
0
ファイル: KeyCreationForm.cs プロジェクト: matt2005/keepass2
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Sign, KPRes.CreateMasterKey,
                                         m_ioInfo.GetDisplayName());
            this.Icon = Properties.Resources.KeePass;
            this.Text = KPRes.CreateMasterKey;

            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
            m_ttRect.SetToolTip(m_btnSaveKeyFile, KPRes.KeyFileCreate);
            m_ttRect.SetToolTip(m_btnOpenKeyFile, KPRes.KeyFileUseExisting);
            m_ttRect.SetToolTip(m_tbRepeatPassword, KPRes.PasswordRepeatHint);

            if (!m_bCreatingNew)
            {
                m_lblIntro.Text = KPRes.ChangeMasterKeyIntroShort;
            }

            m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblRepeatPassword,
                                 m_tbRepeatPassword, m_lblEstimatedQuality, m_pbPasswordQuality,
                                 m_lblQualityBits, this, true, false);

            m_cmbKeyFile.Items.Add(KPRes.NoKeyFileSpecifiedMeta);
            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                m_cmbKeyFile.Items.Add(prov.Name);
            }

            m_cmbKeyFile.SelectedIndex = 0;

            m_cbPassword.Checked = true;
            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyCreationFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if (WinUtil.IsWindows9x || NativeLib.IsUnix())
            {
                UIUtil.SetChecked(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc2, false);
            }

            CustomizeForScreenReader();
            EnableUserControls();
        }
コード例 #4
0
 public IOConnectionInfo GetFilePath(IOConnectionInfo folderPath, string filename)
 {
     try
     {
         return(IOConnectionInfo.FromPath(
                    ListContents(folderPath).Where(desc => { return desc.DisplayName == filename; })
                    .Single()
                    .Path));
     }
     catch (Exception e)
     {
         throw new Exception("Error finding " + filename + " in " + folderPath.GetDisplayName(), e);
     }
 }
コード例 #5
0
        public static bool?Import(PwDatabase pd, FileFormatProvider fmtImp,
                                  IOConnectionInfo iocImp, PwMergeMethod mm, CompositeKey cmpKey)
        {
            if (pd == null)
            {
                Debug.Assert(false); return(false);
            }
            if (fmtImp == null)
            {
                Debug.Assert(false); return(false);
            }
            if (iocImp == null)
            {
                Debug.Assert(false); return(false);
            }
            if (cmpKey == null)
            {
                cmpKey = new CompositeKey();
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            PwDatabase pdImp = new PwDatabase();

            pdImp.New(new IOConnectionInfo(), cmpKey);
            pdImp.MemoryProtection = pd.MemoryProtection.CloneDeep();

            Stream s = IOConnection.OpenRead(iocImp);

            if (s == null)
            {
                throw new FileNotFoundException(iocImp.GetDisplayName() +
                                                MessageService.NewLine + KPRes.FileNotFoundError);
            }

            try { fmtImp.Import(pdImp, s, null); }
            finally { s.Close(); }

            pd.MergeIn(pdImp, mm);
            return(true);
        }
コード例 #6
0
ファイル: FileLock.cs プロジェクト: Stoom/KeePass
        public FileLock(IOConnectionInfo iocBaseFile)
        {
            if(iocBaseFile == null) throw new ArgumentNullException("strBaseFile");

            m_iocLockFile = iocBaseFile.CloneDeep();
            m_iocLockFile.Path += LockFileExt;

            LockFileInfo lfiEx = LockFileInfo.Load(m_iocLockFile);
            if(lfiEx != null)
            {
                m_iocLockFile = null; // Otherwise Dispose deletes the existing one
                throw new FileLockException(iocBaseFile.GetDisplayName(),
                    lfiEx.GetOwner());
            }

            LockFileInfo.Create(m_iocLockFile);
        }
コード例 #7
0
ファイル: OathHotpKeyProv.cs プロジェクト: pythe/wristpass
        public static bool CreateAuxFile(OtpInfo otpInfo,
			KeyProviderQueryContext ctx, IOConnectionInfo auxFileIoc)
        {
            otpInfo.Type = ProvType;
            otpInfo.Version = ProvVersion;
            otpInfo.Generator = ProductName;

            otpInfo.EncryptSecret();

            if(!OtpInfo.Save(auxFileIoc, otpInfo))
            {
                MessageService.ShowWarning("Failed to save auxiliary OTP info file:",
                    auxFileIoc.GetDisplayName());
                return false;
            }

            return true;
        }
コード例 #8
0
ファイル: OathHotpKeyProv.cs プロジェクト: 77rusa/README
        public static bool CreateAuxFile(OtpInfo otpInfo,
                                         KeyProviderQueryContext ctx, IOConnectionInfo auxFileIoc)
        {
            otpInfo.Type      = ProvType;
            otpInfo.Version   = ProvVersion;
            otpInfo.Generator = ProductName;

            otpInfo.EncryptSecret();

            if (!OtpInfo.Save(auxFileIoc, otpInfo))
            {
                MessageService.ShowWarning("Failed to save auxiliary OTP info file:",
                                           auxFileIoc.GetDisplayName());
                return(false);
            }

            return(true);
        }
コード例 #9
0
        private static byte[] Open(KeyProviderQueryContext ctx)
        {
            IOConnectionInfo ioc = GetAuxFileIoc(ctx);

            Info Info = Info.Load(ioc);

            if (Info == null)
            {
                MessageService.ShowWarning("Failed to load auxiliary OTP info file:",
                                           ioc.GetDisplayName());

                Info = new Info();

                Login dlgRec = new Login();
                dlgRec.InitEx(Info, ctx);
                if (UIUtil.ShowDialogAndDestroy(dlgRec) != DialogResult.OK)
                {
                    return(null);
                }

                return(Info.Secret);
            }

            Login dlg = new Login();

            UIUtil.ShowDialogAndDestroy(dlg);

            if (System.Text.Encoding.UTF8.GetString(dlg.Access()) != System.Text.Encoding.UTF8.GetString(Info.Secret))
            {
                return(null);
            }



            if (!CreateAuxFile(Info, ctx))
            {
                return(null);
            }

            return(Info.Secret);
        }
コード例 #10
0
ファイル: IOConnectionForm.cs プロジェクト: matt2005/keepass2
        private bool TestConnectionEx()
        {
            bool bResult = true;
            bool bOK = m_btnOK.Enabled, bCancel = m_btnCancel.Enabled;
            bool bCombo = m_cmbCredSaveMode.Enabled;

            m_btnOK.Enabled           = m_btnCancel.Enabled = m_tbUrl.Enabled =
                m_tbUserName.Enabled  = m_tbPassword.Enabled =
                    m_btnHelp.Enabled = m_cmbCredSaveMode.Enabled = false;

            Application.DoEvents();

            try
            {
                if (!IOConnection.FileExists(m_ioc, true))
                {
                    throw new FileNotFoundException();
                }
            }
            catch (Exception exTest)
            {
                string strError = exTest.Message;
                if ((exTest.InnerException != null) &&
                    !string.IsNullOrEmpty(exTest.InnerException.Message))
                {
                    strError += MessageService.NewParagraph +
                                exTest.InnerException.Message;
                }

                MessageService.ShowWarning(m_ioc.GetDisplayName(), strError);
                bResult = false;
            }

            m_btnOK.Enabled           = bOK;
            m_btnCancel.Enabled       = bCancel;
            m_cmbCredSaveMode.Enabled = bCombo;
            m_btnHelp.Enabled         = m_tbUserName.Enabled = m_tbUrl.Enabled =
                m_tbPassword.Enabled  = true;
            return(bResult);
        }
コード例 #11
0
ファイル: FileLock.cs プロジェクト: Stoom/KeePass
            // Throws on error
            public static LockFileInfo Create(IOConnectionInfo iocLockFile)
            {
                LockFileInfo lfi;
                Stream s = null;
                try
                {
                    byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16);
                    string strTime = TimeUtil.SerializeUtc(DateTime.Now);

                    lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime,
                #if KeePassUAP
                        EnvironmentExt.UserName, EnvironmentExt.MachineName,
                        EnvironmentExt.UserDomainName);
                #elif KeePassLibSD
                        string.Empty, string.Empty, string.Empty);
                #else
                        Environment.UserName, Environment.MachineName,
                        Environment.UserDomainName);
                #endif

                    StringBuilder sb = new StringBuilder();
                #if !KeePassLibSD
                    sb.AppendLine(LockFileHeader);
                    sb.AppendLine(lfi.ID);
                    sb.AppendLine(strTime);
                    sb.AppendLine(lfi.UserName);
                    sb.AppendLine(lfi.Machine);
                    sb.AppendLine(lfi.Domain);
                #else
                    sb.Append(LockFileHeader + MessageService.NewLine);
                    sb.Append(lfi.ID + MessageService.NewLine);
                    sb.Append(strTime + MessageService.NewLine);
                    sb.Append(lfi.UserName + MessageService.NewLine);
                    sb.Append(lfi.Machine + MessageService.NewLine);
                    sb.Append(lfi.Domain + MessageService.NewLine);
                #endif

                    byte[] pbFile = StrUtil.Utf8.GetBytes(sb.ToString());

                    s = IOConnection.OpenWrite(iocLockFile);
                    if(s == null) throw new IOException(iocLockFile.GetDisplayName());
                    s.Write(pbFile, 0, pbFile.Length);
                }
                finally { if(s != null) s.Close(); }

                return lfi;
            }
コード例 #12
0
ファイル: ImportUtil.cs プロジェクト: riking/go-keepass2
		public static bool? Import(PwDatabase pd, FileFormatProvider fmtImp,
			IOConnectionInfo iocImp, PwMergeMethod mm, CompositeKey cmpKey)
		{
			if(pd == null) { Debug.Assert(false); return false; }
			if(fmtImp == null) { Debug.Assert(false); return false; }
			if(iocImp == null) { Debug.Assert(false); return false; }
			if(cmpKey == null) cmpKey = new CompositeKey();

			if(!AppPolicy.Try(AppPolicyId.Import)) return false;
			if(!fmtImp.TryBeginImport()) return false;

			PwDatabase pdImp = new PwDatabase();
			pdImp.New(new IOConnectionInfo(), cmpKey);
			pdImp.MemoryProtection = pd.MemoryProtection.CloneDeep();

			Stream s = IOConnection.OpenRead(iocImp);
			if(s == null)
				throw new FileNotFoundException(iocImp.GetDisplayName() +
					MessageService.NewLine + KPRes.FileNotFoundError);

			try { fmtImp.Import(pdImp, s, null); }
			finally { s.Close(); }

			pd.MergeIn(pdImp, mm);
			return true;
		}
コード例 #13
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            // The password text box should not be focused by default
            // in order to avoid a Caps Lock warning tooltip bug;
            // https://sourceforge.net/p/keepass/bugs/1807/
            Debug.Assert((m_tbPassword.TabIndex >= 2) && !m_tbPassword.Focused);

            GlobalWindowManager.AddWindow(this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Sign, KPRes.CreateMasterKey,
                                         m_ioInfo.GetDisplayName());
            this.Icon = AppIcons.Default;
            this.Text = KPRes.CreateMasterKey;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            m_imgKeyFileWarning = UIUtil.IconToBitmap(SystemIcons.Warning,
                                                      DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));
            m_imgAccWarning           = (Image)m_imgKeyFileWarning.Clone();
            m_picKeyFileWarning.Image = m_imgKeyFileWarning;
            m_picAccWarning.Image     = m_imgAccWarning;

            UIUtil.ConfigureToolTip(m_ttRect);
            UIUtil.SetToolTip(m_ttRect, m_tbRepeatPassword, KPRes.PasswordRepeatHint, false);
            UIUtil.SetToolTip(m_ttRect, m_btnSaveKeyFile, KPRes.KeyFileCreate, false);
            UIUtil.SetToolTip(m_ttRect, m_btnOpenKeyFile, KPRes.KeyFileUseExisting, false);

            UIUtil.AccSetName(m_tbPassword, m_cbPassword);
            UIUtil.AccSetName(m_cmbKeyFile, m_cbKeyFile);
            UIUtil.AccSetName(m_picKeyFileWarning, KPRes.Warning);
            UIUtil.AccSetName(m_picAccWarning, KPRes.Warning);

            Debug.Assert(!m_lblIntro.AutoSize);             // For RTL support
            if (!m_bCreatingNew)
            {
                m_lblIntro.Text = KPRes.ChangeMasterKeyIntroShort;
            }

            m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblRepeatPassword,
                                 m_tbRepeatPassword, m_lblEstimatedQuality, m_pbPasswordQuality,
                                 m_lblQualityInfo, m_ttRect, this, true, false);

            m_cmbKeyFile.Items.Add(KPRes.NoKeyFileSpecifiedMeta);
            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                m_cmbKeyFile.Items.Add(prov.Name);
            }

            m_cmbKeyFile.SelectedIndex = 0;

            m_cbPassword.Checked = true;
            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyCreationFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if (WinUtil.IsWindows9x || NativeLib.IsUnix())
            {
                UIUtil.SetChecked(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc2, false);
            }

            EnableUserControls();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
コード例 #14
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            ++m_uUIAutoBlocked;

            // The password text box should not be focused by default
            // in order to avoid a Caps Lock warning tooltip bug;
            // https://sourceforge.net/p/keepass/bugs/1807/
            Debug.Assert((m_tbPassword.TabIndex >= 2) && !m_tbPassword.Focused);

            GlobalWindowManager.AddWindow(this);
            // if(m_bRedirectActivation) Program.MainForm.RedirectActivationPush(this);

            string strBannerTitle = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                                     m_strCustomTitle : KPRes.EnterCompositeKey);
            string strBannerDesc = m_ioInfo.GetDisplayName();             // Compacted by banner

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Key2, strBannerTitle, strBannerDesc);
            this.Icon = AppIcons.Default;

            string strStart = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                               m_strCustomTitle : KPRes.OpenDatabase);
            string strName = UrlUtil.GetFileName(m_ioInfo.Path);

            if (!string.IsNullOrEmpty(strName))
            {
                this.Text = strStart + " - " + strName;
            }
            else
            {
                this.Text = strStart;
            }

            FontUtil.SetDefaultFont(m_cbPassword);
            // FontUtil.AssignDefaultBold(m_cbPassword);
            // FontUtil.AssignDefaultBold(m_cbKeyFile);
            // FontUtil.AssignDefaultBold(m_cbUserAccount);

            UIUtil.ConfigureToolTip(m_ttRect);
            UIUtil.SetToolTip(m_ttRect, m_btnOpenKeyFile, KPRes.KeyFileSelect, true);

            UIUtil.AccSetName(m_tbPassword, m_cbPassword);
            UIUtil.AccSetName(m_cmbKeyFile, m_cbKeyFile);

            PwInputControlGroup.ConfigureHideButton(m_cbHidePassword, m_ttRect);

            // Enable protection before possibly setting a text
            m_cbHidePassword.Checked = true;
            OnHidePasswordCheckedChanged(null, EventArgs.Empty);

            // Must be set manually due to possible object override
            m_tbPassword.TextChanged += this.OnPasswordTextChanged;

            // m_cmbKeyFile.OrderedImageList = m_lKeyFileImages;
            AddKeyFileItem(KPRes.NoKeyFileSpecifiedMeta, true);

            Debug.Assert(!AnyComponentOn());

            // Do not directly compare with Program.CommandLineArgs.FileName,
            // because this may be a relative path instead of an absolute one
            string strCmdLineFile = Program.CommandLineArgs.FileName;

            if (!string.IsNullOrEmpty(strCmdLineFile) && (Program.MainForm != null))
            {
                strCmdLineFile = Program.MainForm.IocFromCommandLine().Path;
            }
            if (!string.IsNullOrEmpty(strCmdLineFile) && strCmdLineFile.Equals(
                    m_ioInfo.Path, StrUtil.CaseIgnoreCmp))
            {
                string str;

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.Password];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = str;
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordEncrypted];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = StrUtil.DecryptString(str);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordStdIn];
                if (str != null)
                {
                    ProtectedString ps = KeyUtil.ReadPasswordStdIn(true);
                    if (ps != null)
                    {
                        m_cbPassword.Checked = true;
                        m_tbPassword.TextEx  = ps;
                    }
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.KeyFile];
                if (!string.IsNullOrEmpty(str))
                {
                    AddKeyFileItem(str, true);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PreSelect];
                if (!string.IsNullOrEmpty(str))
                {
                    AddKeyFileItem(str, true);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.UserAccount];
                if (str != null)
                {
                    m_cbUserAccount.Checked = true;
                }
            }

            AceKeyAssoc a = Program.Config.Defaults.GetKeySources(m_ioInfo);

            if ((a != null) && !AnyComponentOn())
            {
                if (a.Password)
                {
                    m_cbPassword.Checked = true;
                }

                if (!string.IsNullOrEmpty(a.KeyFilePath))
                {
                    AddKeyFileItem(a.KeyFilePath, true);
                }
                if (!string.IsNullOrEmpty(a.KeyProvider))
                {
                    AddKeyFileItem(a.KeyProvider, true);
                }

                if (a.UserAccount)
                {
                    m_cbUserAccount.Checked = true;
                }
            }

            foreach (KeyProvider kp in Program.KeyProviderPool)
            {
                AddKeyFileItem(kp.Name, false);
            }

            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyPromptFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if (!m_cbPassword.Enabled && !m_cbPassword.Checked)
            {
                m_tbPassword.Text = string.Empty;
                UIUtil.SetEnabledFast(false, m_tbPassword, m_cbHidePassword);
            }

            if (!m_cbKeyFile.Enabled && !m_cbKeyFile.Checked)
            {
                UIUtil.SetEnabledFast(false, m_cmbKeyFile, m_btnOpenKeyFile);
            }

            if (WinUtil.IsWindows9x || NativeLib.IsUnix())
            {
                UIUtil.SetChecked(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_cbUserAccount, false);
            }

            m_btnExit.Enabled = m_bCanExit;
            m_btnExit.Visible = m_bCanExit;

            --m_uUIAutoBlocked;
            UpdateUIState();

            // Local, but thread will continue to run anyway
            Thread th = new Thread(new ThreadStart(this.OnFormLoadAsync));

            th.Start();
            // ThreadPool.QueueUserWorkItem(new WaitCallback(this.OnFormLoadAsync));

            this.BringToFront();
            this.Activate();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
コード例 #15
0
ファイル: BuiltInFileStorage.cs プロジェクト: pythe/wristpass
 public string GetDisplayName(IOConnectionInfo ioc)
 {
     return ioc.GetDisplayName();
 }
コード例 #16
0
		private bool FixDuplicateUuids(PwDatabase pd, IOConnectionInfo ioc)
		{
			if(pd == null) { Debug.Assert(false); return false; }

			if(!pd.HasDuplicateUuids()) return false;

			string str = string.Empty;
			if(ioc != null)
			{
				string strFile = ioc.GetDisplayName();
				if(!string.IsNullOrEmpty(strFile))
					str += strFile + MessageService.NewParagraph;
			}

			str += KPRes.UuidDupInDb + MessageService.NewParagraph +
				KPRes.CorruptionByExt + MessageService.NewParagraph +
				KPRes.UuidFix;

			if(VistaTaskDialog.ShowMessageBoxEx(str, null,
				PwDefs.ShortProductName, VtdIcon.Warning, null,
				KPRes.RepairCmd, (int)DialogResult.Cancel, null, 0) < 0)
				MessageService.ShowWarning(str);

			pd.FixDuplicateUuids();
			pd.Modified = true;
			return true;
		}
コード例 #17
0
		private void PostSavingEx(bool bPrimary, PwDatabase pwDatabase,
			IOConnectionInfo ioc, IStatusLogger sl)
		{
			if(ioc == null) { Debug.Assert(false); return; }

			byte[] pbIO = null;
			if(Program.Config.Application.VerifyWrittenFileAfterSaving)
			{
				pbIO = WinUtil.HashFile(ioc);
				Debug.Assert((pbIO != null) && (pwDatabase.HashOfLastIO != null));
				if(!MemUtil.ArraysEqual(pbIO, pwDatabase.HashOfLastIO))
					MessageService.ShowWarning(ioc.GetDisplayName(),
						KPRes.FileVerifyHashFail, KPRes.FileVerifyHashFailRec);
			}

			if(bPrimary)
			{
#if DEBUG
				Debug.Assert(MemUtil.ArraysEqual(pbIO, pwDatabase.HashOfFileOnDisk));

				try
				{
					PwDatabase pwCheck = new PwDatabase();
					pwCheck.Open(ioc.CloneDeep(), pwDatabase.MasterKey, null);

					Debug.Assert(MemUtil.ArraysEqual(pwDatabase.HashOfLastIO,
						pwCheck.HashOfLastIO));

					uint uGroups1, uGroups2, uEntries1, uEntries2;
					pwDatabase.RootGroup.GetCounts(true, out uGroups1, out uEntries1);
					pwCheck.RootGroup.GetCounts(true, out uGroups2, out uEntries2);
					Debug.Assert((uGroups1 == uGroups2) && (uEntries1 == uEntries2));
				}
				catch(Exception exVerify) { Debug.Assert(false, exVerify.Message); }
#endif

				m_mruList.AddItem(ioc.GetDisplayName(), ioc.CloneDeep());

				// SetLastUsedFile(ioc);

				// if(Program.Config.Application.CreateBackupFileAfterSaving && bHashValid)
				// {
				//	try { pwDatabase.CreateBackupFile(sl); }
				//	catch(Exception exBackup)
				//	{
				//		MessageService.ShowWarning(KPRes.FileBackupFailed, exBackup);
				//	}
				// }

				// ulong uTotalBinSize = 0;
				// EntryHandler ehCnt = delegate(PwEntry pe)
				// {
				//	foreach(KeyValuePair<string, ProtectedBinary> kvpCnt in pe.Binaries)
				//	{
				//		uTotalBinSize += kvpCnt.Value.Length;
				//	}
				//
				//	return true;
				// };
				// pwDatabase.RootGroup.TraverseTree(TraversalMethod.PreOrder, null, ehCnt);
			}

			RememberKeySources(pwDatabase);
			WinUtil.FlushStorageBuffers(ioc.Path, true);
		}
コード例 #18
0
ファイル: BuiltInFileStorage.cs プロジェクト: 77rusa/README
 public string GetDisplayName(IOConnectionInfo ioc)
 {
     return(ioc.GetDisplayName());
 }
コード例 #19
0
ファイル: TimeoutHelper.cs プロジェクト: pythe/wristpass
 static bool IocChanged(IOConnectionInfo ioc, IOConnectionInfo other)
 {
     if ((ioc == null) || (other == null)) return false;
     return ioc.GetDisplayName() != other.GetDisplayName();
 }
コード例 #20
0
        private void PostSavingEx(bool bPrimary, PwDatabase pwDatabase, IOConnectionInfo ioc)
        {
            if(ioc == null) { Debug.Assert(false); return; }

            byte[] pbIO = WinUtil.HashFile(ioc);
            Debug.Assert((pbIO != null) && (pwDatabase.HashOfLastIO != null));
            if(pwDatabase.HashOfLastIO != null)
            {
                if(!MemUtil.ArraysEqual(pbIO, pwDatabase.HashOfLastIO))
                {
                    MessageService.ShowWarning(ioc.GetDisplayName(), KPRes.FileVerifyHashFail,
                        KPRes.FileVerifyHashFailRec);
                }
            }

            if(bPrimary)
            {
            #if DEBUG
                Debug.Assert(MemUtil.ArraysEqual(pbIO, pwDatabase.HashOfFileOnDisk));

                try
                {
                    PwDatabase pwCheck = new PwDatabase();
                    pwCheck.Open(ioc.CloneDeep(), pwDatabase.MasterKey, null);

                    Debug.Assert(MemUtil.ArraysEqual(pwDatabase.HashOfLastIO,
                        pwCheck.HashOfLastIO));

                    uint uGroups1, uGroups2, uEntries1, uEntries2;
                    pwDatabase.RootGroup.GetCounts(true, out uGroups1, out uEntries1);
                    pwCheck.RootGroup.GetCounts(true, out uGroups2, out uEntries2);
                    Debug.Assert((uGroups1 == uGroups2) && (uEntries1 == uEntries2));
                }
                catch(Exception exVerify) { Debug.Assert(false, exVerify.Message); }
            #endif

                m_mruList.AddItem(ioc.GetDisplayName(), ioc.CloneDeep());

                Program.Config.Application.LastUsedFile = ioc.CloneDeep();
            }

            WinUtil.FlushStorageBuffers(ioc.Path, true);
        }
コード例 #21
0
ファイル: KeyCreationForm.cs プロジェクト: fsdsabel/keepass
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Sign, KPRes.CreateMasterKey,
                                         m_ioInfo.GetDisplayName());
            this.Icon = AppIcons.Default;
            this.Text = KPRes.CreateMasterKey;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            Bitmap bmpBig = SystemIcons.Warning.ToBitmap();

            m_imgAccWarning = GfxUtil.ScaleImage(bmpBig, DpiUtil.ScaleIntX(16),
                                                 DpiUtil.ScaleIntY(16), ScaleTransformFlags.UIIcon);
            bmpBig.Dispose();
            m_picAccWarning.Image = m_imgAccWarning;

            UIUtil.ConfigureToolTip(m_ttRect);
            // m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
            m_ttRect.SetToolTip(m_btnSaveKeyFile, KPRes.KeyFileCreate);
            m_ttRect.SetToolTip(m_btnOpenKeyFile, KPRes.KeyFileUseExisting);
            m_ttRect.SetToolTip(m_tbRepeatPassword, KPRes.PasswordRepeatHint);

            Debug.Assert(!m_lblIntro.AutoSize);             // For RTL support
            if (!m_bCreatingNew)
            {
                m_lblIntro.Text = KPRes.ChangeMasterKeyIntroShort;
            }

            m_icgPassword.Attach(m_tbPassword, m_cbHidePassword, m_lblRepeatPassword,
                                 m_tbRepeatPassword, m_lblEstimatedQuality, m_pbPasswordQuality,
                                 m_lblQualityInfo, m_ttRect, this, true, false);

            m_cmbKeyFile.Items.Add(KPRes.NoKeyFileSpecifiedMeta);
            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                m_cmbKeyFile.Items.Add(prov.Name);
            }

            m_cmbKeyFile.SelectedIndex = 0;

            m_cbPassword.Checked = true;
            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyCreationFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if (WinUtil.IsWindows9x || NativeLib.IsUnix())
            {
                UIUtil.SetChecked(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_cbUserAccount, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc, false);
                UIUtil.SetEnabled(m_lblWindowsAccDesc2, false);
            }

            CustomizeForScreenReader();
            EnableUserControls();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
コード例 #22
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            m_bInitializing = true;

            // The password text box should not be focused by default
            // in order to avoid a Caps Lock warning tooltip bug;
            // https://sourceforge.net/p/keepass/bugs/1807/
            Debug.Assert((m_tbPassword.TabIndex >= 2) && !m_tbPassword.Focused);

            GlobalWindowManager.AddWindow(this);
            // if(m_bRedirectActivation) Program.MainForm.RedirectActivationPush(this);

            string strBannerTitle = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                                     m_strCustomTitle : KPRes.EnterCompositeKey);
            string strBannerDesc = m_ioInfo.GetDisplayName();             // Compacted by banner

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Key2, strBannerTitle, strBannerDesc);
            this.Icon = AppIcons.Default;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            UIUtil.ConfigureToolTip(m_ttRect);
            UIUtil.SetToolTip(m_ttRect, m_btnOpenKeyFile, KPRes.KeyFileSelect, true);

            UIUtil.AccSetName(m_tbPassword, m_cbPassword);
            UIUtil.AccSetName(m_cmbKeyFile, m_cbKeyFile);

            PwInputControlGroup.ConfigureHideButton(m_cbHidePassword, m_ttRect);

            string strStart = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                               m_strCustomTitle : KPRes.OpenDatabase);
            string strNameEx = UrlUtil.GetFileName(m_ioInfo.Path);

            if (!string.IsNullOrEmpty(strNameEx))
            {
                this.Text = strStart + " - " + strNameEx;
            }
            else
            {
                this.Text = strStart;
            }

            // Must be set manually due to possible object override
            m_tbPassword.TextChanged += this.ProcessTextChangedPassword;

            // m_cmbKeyFile.OrderedImageList = m_lKeyFileImages;
            AddKeyFileSuggPriv(KPRes.NoKeyFileSpecifiedMeta, true);

            // Enable protection before possibly setting a text
            m_cbHidePassword.Checked = true;
            OnCheckedHidePassword(sender, e);             // 'Checked' may have been true already

            // Do not directly compare with Program.CommandLineArgs.FileName,
            // because this may be a relative path instead of an absolute one
            string strCmdLineFile = Program.CommandLineArgs.FileName;

            if ((strCmdLineFile != null) && (Program.MainForm != null))
            {
                strCmdLineFile = Program.MainForm.IocFromCommandLine().Path;
            }
            if ((strCmdLineFile != null) && strCmdLineFile.Equals(m_ioInfo.Path,
                                                                  StrUtil.CaseIgnoreCmp))
            {
                string str;

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.Password];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = str;
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordEncrypted];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = StrUtil.DecryptString(str);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordStdIn];
                if (str != null)
                {
                    ProtectedString ps = KeyUtil.ReadPasswordStdIn(true);
                    if (ps != null)
                    {
                        m_cbPassword.Checked = true;
                        m_tbPassword.TextEx  = ps;
                    }
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.KeyFile];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;
                    AddKeyFileSuggPriv(str, true);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PreSelect];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;
                    AddKeyFileSuggPriv(str, true);
                }
            }

            Debug.Assert(m_cmbKeyFile.Text.Length != 0);

            m_btnExit.Enabled = m_bCanExit;
            m_btnExit.Visible = m_bCanExit;

            ulong uKpf = Program.Config.UI.KeyPromptFlags;

            UIUtil.ApplyKeyUIFlags(uKpf, m_cbPassword, m_cbKeyFile,
                                   m_cbUserAccount, m_cbHidePassword);

            if ((uKpf & (ulong)AceKeyUIFlags.DisableKeyFile) != 0)
            {
                UIUtil.SetEnabled(m_cmbKeyFile, m_cbKeyFile.Checked);
                UIUtil.SetEnabled(m_btnOpenKeyFile, m_cbKeyFile.Checked);
            }

            if (((uKpf & (ulong)AceKeyUIFlags.CheckPassword) != 0) ||
                ((uKpf & (ulong)AceKeyUIFlags.UncheckPassword) != 0))
            {
                m_bPwStatePreset = true;
            }
            if (((uKpf & (ulong)AceKeyUIFlags.CheckUserAccount) != 0) ||
                ((uKpf & (ulong)AceKeyUIFlags.UncheckUserAccount) != 0))
            {
                m_bUaStatePreset = true;
            }

            EnableUserControls();

            m_bInitializing = false;

            // E.g. command line options have higher priority
            m_bCanModKeyFile = (m_cmbKeyFile.SelectedIndex == 0);

            m_aKeyAssoc = Program.Config.Defaults.GetKeySources(m_ioInfo);
            if (m_aKeyAssoc != null)
            {
                if (m_aKeyAssoc.Password && !m_bPwStatePreset)
                {
                    m_cbPassword.Checked = true;
                }

                if (m_aKeyAssoc.KeyFilePath.Length > 0)
                {
                    AddKeyFileSuggPriv(m_aKeyAssoc.KeyFilePath, null);
                }

                if (m_aKeyAssoc.UserAccount && !m_bUaStatePreset)
                {
                    m_cbUserAccount.Checked = true;
                }
            }

            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                AddKeyFileSuggPriv(prov.Name, null);
            }

            // Local, but thread will continue to run anyway
            Thread th = new Thread(new ThreadStart(this.AsyncFormLoad));

            th.Start();
            // ThreadPool.QueueUserWorkItem(new WaitCallback(this.AsyncFormLoad));

            this.BringToFront();
            this.Activate();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
コード例 #23
0
ファイル: PasswordActivity.cs プロジェクト: pythe/wristpass
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyTheme();

            //use FlagSecure to make sure the last (revealed) character of the master password is not visible in recent apps
            if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(
                GetString(Resource.String.ViewDatabaseSecure_key), true))
            {
                Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            }

            Intent i = Intent;

            //only load the AppTask if this is the "first" OnCreate (not because of kill/resume, i.e. savedInstanceState==null)
            // and if the activity is not launched from history (i.e. recent tasks) because this would mean that
            // the Activity was closed already (user cancelling the task or task complete) but is restarted due recent tasks.
            // Don't re-start the task (especially bad if tak was complete already)
            if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
            {
                AppTask = new NullTask();
            }
            else
            {
                AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
            }

            String action = i.Action;

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            _rememberKeyfile = _prefs.GetBoolean(GetString(Resource.String.keyfile_key), Resources.GetBoolean(Resource.Boolean.keyfile_default));

            _ioConnection = new IOConnectionInfo();

            if (action != null && action.Equals(ViewIntent))
            {
                if (!GetIocFromViewIntent(i)) return;
            }
            else if ((action != null) && (action.Equals(Intents.StartWithOtp)))
            {
                if (!GetIocFromOtpIntent(savedInstanceState, i)) return;
                _keepPasswordInOnResume = true;
            }
            else
            {
                SetIoConnectionFromIntent(_ioConnection, i);
                var keyFileFromIntent = i.GetStringExtra(KeyKeyfile);
                if (keyFileFromIntent != null)
                {
                    Kp2aLog.Log("try get keyfile from intent");
                    _keyFileOrProvider = IOConnectionInfo.SerializeToString(IOConnectionInfo.FromPath(keyFileFromIntent));
                    Kp2aLog.Log("try get keyfile from intent ok");
                }
                else
                {
                    _keyFileOrProvider = null;
                }
                _password = i.GetStringExtra(KeyPassword) ?? "";
                if (string.IsNullOrEmpty(_keyFileOrProvider))
                {
                    _keyFileOrProvider = GetKeyFile(_ioConnection.Path);
                }
                if ((!string.IsNullOrEmpty(_keyFileOrProvider)) || (_password != ""))
                {
                    _keepPasswordInOnResume = true;
                }
            }

            if (App.Kp2a.GetDb().Loaded && App.Kp2a.GetDb().Ioc != null &&
                App.Kp2a.GetDb().Ioc.GetDisplayName() != _ioConnection.GetDisplayName())
            {
                // A different database is currently loaded, unload it before loading the new one requested
                App.Kp2a.LockDatabase(false);
            }

            SetContentView(Resource.Layout.password);
            InitializeFilenameView();

            if (KeyProviderType == KeyProviders.KeyFile)
            {
                UpdateKeyfileIocView();
            }

            FindViewById<EditText>(Resource.Id.password).TextChanged +=
                (sender, args) =>
                {
                    _password = FindViewById<EditText>(Resource.Id.password).Text;
                    UpdateOkButtonState();
                };
            FindViewById<EditText>(Resource.Id.password).EditorAction += (sender, args) =>
                {
                    if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down)))
                        OnOk();
                };

            FindViewById<EditText>(Resource.Id.pass_otpsecret).TextChanged += (sender, args) => UpdateOkButtonState();

            EditText passwordEdit = FindViewById<EditText>(Resource.Id.password);
            passwordEdit.Text = _password;
            passwordEdit.RequestFocus();
            Window.SetSoftInputMode(SoftInput.StateVisible);

            InitializeOkButton();

            InitializePasswordModeSpinner();

            InitializeOtpSecretSpinner();

            UpdateOkButtonState();

            InitializeTogglePasswordButton();
            InitializeKeyfileBrowseButton();

            InitializeQuickUnlockCheckbox();

            RestoreState(savedInstanceState);

            if (i.GetBooleanExtra("launchImmediately", false))
            {
                App.Kp2a.GetFileStorage(_ioConnection)
                       .PrepareFileUsage(new FileStorageSetupInitiatorActivity(this, OnActivityResult, null), _ioConnection,
                                         RequestCodePrepareDbFile, false);
            }
        }
コード例 #24
0
		private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc,
			CompositeKey cmpKey, out bool bAbort)
		{
			bAbort = false;

			PerformSelfTest();

			ShowWarningsLogger swLogger = CreateShowWarningsLogger();
			swLogger.StartLogging(KPRes.OpeningDatabase, true);

			PwDocument ds = null;
			string strPathNrm = ioc.Path.Trim().ToLower();
			for(int iScan = 0; iScan < m_docMgr.Documents.Count; ++iScan)
			{
				if(m_docMgr.Documents[iScan].LockedIoc.Path.Trim().ToLower() == strPathNrm)
					ds = m_docMgr.Documents[iScan];
				else if(m_docMgr.Documents[iScan].Database.IOConnectionInfo.Path == strPathNrm)
					ds = m_docMgr.Documents[iScan];
			}

			PwDatabase pwDb;
			if(ds == null) pwDb = m_docMgr.CreateNewDocument(true).Database;
			else pwDb = ds.Database;

			Exception ex = null;
			try
			{
				pwDb.Open(ioc, cmpKey, swLogger);

#if DEBUG
				byte[] pbDiskDirect = WinUtil.HashFile(ioc);
				Debug.Assert(MemUtil.ArraysEqual(pbDiskDirect, pwDb.HashOfFileOnDisk));
#endif
			}
			catch(Exception exLoad)
			{
				ex = exLoad;
				pwDb = null;
			}

			swLogger.EndLogging();

			if(pwDb == null)
			{
				if(ds == null) m_docMgr.CloseDatabase(m_docMgr.ActiveDatabase);
			}

			if(ex != null)
			{
				string strMsg = MessageService.GetLoadWarningMessage(
					ioc.GetDisplayName(), ex,
					(Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null));

				bool bShowStd = true;
				if(!ioc.IsLocalFile())
				{
					VistaTaskDialog vtd = new VistaTaskDialog();
					vtd.CommandLinks = false;
					vtd.Content = strMsg;
					vtd.DefaultButtonID = (int)DialogResult.Cancel;
					// vtd.VerificationText = KPRes.CredSpecifyDifferent;
					vtd.WindowTitle = PwDefs.ShortProductName;

					vtd.SetIcon(VtdIcon.Warning);
					vtd.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
					vtd.AddButton((int)DialogResult.Retry,
						KPRes.CredSpecifyDifferent, null);

					if(vtd.ShowDialog(this))
					{
						bShowStd = false;

						// if(vtd.ResultVerificationChecked)
						if(vtd.Result == (int)DialogResult.Retry)
						{
							IOConnectionInfo iocNew = ioc.CloneDeep();
							// iocNew.ClearCredentials(false);
							iocNew.CredSaveMode = IOCredSaveMode.NoSave;
							iocNew.IsComplete = false;
							// iocNew.Password = string.Empty;

							OpenDatabase(iocNew, null, false);

							bAbort = true;
						}
					}
				}

				if(bShowStd) MessageService.ShowWarning(strMsg);
				// MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex,
				//	(Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null));
			}

			return pwDb;
		}
コード例 #25
0
        private static void RunScriptLine(CommandLineArgs args)
        {
            string strCommand = args[ParamCommand];

            if (strCommand == null)
            {
                throw new InvalidOperationException(KSRes.NoCommand);
            }

            if (args.FileName == null)
            {
                RunSingleCommand(strCommand.ToLower());
                return;
            }

            IOConnectionInfo ioc = new IOConnectionInfo();

            ioc.Url          = args.FileName;
            ioc.CredSaveMode = IOCredSaveMode.NoSave;

            CompositeKey cmpKey = null;

            if (args[ParamGuiKey] != null)
            {
                EnsureGuiInitialized();
                KeyPromptForm kpf = new KeyPromptForm();
                kpf.InitEx(ioc.GetDisplayName(), false);
                if (kpf.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                cmpKey = kpf.CompositeKey;
            }
            else if (args[ParamConsoleKey] != null)
            {
                cmpKey = new CompositeKey();

                Console.WriteLine(KSRes.NoKeyPartHint);
                Console.WriteLine();
                Console.WriteLine(KSRes.KeyPrompt);

                Console.Write(KSRes.PasswordPrompt + " ");
                string strPw = Console.ReadLine().Trim();
                if ((strPw != null) && (strPw.Length > 0))
                {
                    cmpKey.AddUserKey(new KcpPassword(strPw));
                }

                Console.Write(KSRes.KeyFilePrompt + " ");
                string strFile = Console.ReadLine().Trim();
                if ((strFile != null) && (strFile.Length > 0))
                {
                    cmpKey.AddUserKey(new KcpKeyFile(strFile));
                }

                Console.Write(KSRes.UserAccountPrompt + " ");
                string strUA = Console.ReadLine().Trim();
                if (strUA != null)
                {
                    string strUal = strUA.ToLower();
                    if ((strUal == "y") || (strUal == "j") ||
                        (strUal == "o") || (strUal == "a") ||
                        (strUal == "u"))
                    {
                        cmpKey.AddUserKey(new KcpUserAccount());
                    }
                }
            }
            else
            {
                cmpKey = KeyFromCmdLine(args);
            }

            PwDatabase pwDb = new PwDatabase();

            pwDb.Open(ioc, cmpKey, null);

            bool bNeedsSave;

            RunFileCommand(strCommand.ToLower(), args, pwDb, out bNeedsSave);

            if (bNeedsSave)
            {
                pwDb.Save(null);
            }

            pwDb.Close();
        }
コード例 #26
0
		private static DialogResult AskIfSynchronizeInstead(IOConnectionInfo ioc)
		{
			VistaTaskDialog dlg = new VistaTaskDialog();

			string strText = string.Empty;
			if(ioc.GetDisplayName().Length > 0)
				strText += ioc.GetDisplayName() + MessageService.NewParagraph;
			strText += KPRes.FileChanged;

			dlg.CommandLinks = true;
			dlg.WindowTitle = PwDefs.ShortProductName;
			dlg.Content = strText;
			dlg.SetIcon(VtdCustomIcon.Question);

			dlg.MainInstruction = KPRes.OverwriteExistingFileQuestion;
			dlg.AddButton((int)DialogResult.Yes, KPRes.Synchronize, KPRes.FileChangedSync);
			dlg.AddButton((int)DialogResult.No, KPRes.Overwrite, KPRes.FileChangedOverwrite);
			dlg.AddButton((int)DialogResult.Cancel, KPRes.Cancel, KPRes.FileSaveQOpCancel);

			DialogResult dr;
			if(dlg.ShowDialog()) dr = (DialogResult)dlg.Result;
			else
			{
				strText += MessageService.NewParagraph;
				strText += @"[" + KPRes.Yes + @"]: " + KPRes.Synchronize + @". " +
					KPRes.FileChangedSync + MessageService.NewParagraph;
				strText += @"[" + KPRes.No + @"]: " + KPRes.Overwrite + @". " +
					KPRes.FileChangedOverwrite + MessageService.NewParagraph;
				strText += @"[" + KPRes.Cancel + @"]: " + KPRes.FileSaveQOpCancel;

				dr = MessageService.Ask(strText, PwDefs.ShortProductName,
					MessageBoxButtons.YesNoCancel);
			}

			return dr;
		}
コード例 #27
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            Debug.Assert(m_pwDatabase != null); if (m_pwDatabase == null)
            {
                throw new InvalidOperationException();
            }

            m_bInitializing = true;

            GlobalWindowManager.AddWindow(this);

            IOConnectionInfo ioc     = m_pwDatabase.IOConnectionInfo;
            string           strDisp = ioc.GetDisplayName();

            string strDesc = KPRes.DatabaseSettingsDesc;

            if (!string.IsNullOrEmpty(strDisp))
            {
                strDesc = strDisp;
            }

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_Ark, KPRes.DatabaseSettings, strDesc);
            this.Icon = AppIcons.Default;

            FontUtil.AssignDefaultItalic(m_lblHeaderCpAlgo);
            FontUtil.AssignDefaultItalic(m_lblHeaderCp);
            FontUtil.AssignDefaultItalic(m_lblHeaderPerf);

            FontUtil.AssignDefaultBold(m_rbNone);
            FontUtil.AssignDefaultBold(m_rbGZip);

            UIUtil.ConfigureToolTip(m_ttRect);
            m_ttRect.SetToolTip(m_btnKdf1Sec, KPRes.KdfParams1Sec);

            m_tbDbName.PromptText = KPRes.DatabaseNamePrompt;
            m_tbDbDesc.PromptText = KPRes.DatabaseDescPrompt;

            if (m_bCreatingNew)
            {
                this.Text = KPRes.ConfigureOnNewDatabase2;
            }
            else
            {
                this.Text = KPRes.DatabaseSettings;
            }

            m_tbDbName.Text = m_pwDatabase.Name;
            UIUtil.SetMultilineText(m_tbDbDesc, m_pwDatabase.Description);
            m_tbDefaultUser.Text = m_pwDatabase.DefaultUserName;

            m_clr = m_pwDatabase.Color;
            if (m_clr != Color.Empty)
            {
                m_clr = AppIcons.RoundColor(m_clr);
                UIUtil.OverwriteButtonImage(m_btnColor, ref m_imgColor,
                                            UIUtil.CreateColorBitmap24(m_btnColor, m_clr));
            }
            m_cbColor.Checked = (m_clr != Color.Empty);

            for (int inx = 0; inx < CipherPool.GlobalPool.EngineCount; ++inx)
            {
                m_cmbEncAlgo.Items.Add(CipherPool.GlobalPool[inx].DisplayName);
            }

            if (m_cmbEncAlgo.Items.Count > 0)
            {
                int nIndex = CipherPool.GlobalPool.GetCipherIndex(m_pwDatabase.DataCipherUuid);
                m_cmbEncAlgo.SelectedIndex = ((nIndex >= 0) ? nIndex : 0);
            }

            Debug.Assert(m_cmbKdf.Items.Count == 0);
            foreach (KdfEngine kdf in KdfPool.Engines)
            {
                m_cmbKdf.Items.Add(kdf.Name);
            }

            m_numKdfIt.Minimum = ulong.MinValue;
            m_numKdfIt.Maximum = ulong.MaxValue;

            m_numKdfMem.Minimum = ulong.MinValue;
            m_numKdfMem.Maximum = ulong.MaxValue;

            Debug.Assert(m_cmbKdfMem.Items.Count == 0);
            Debug.Assert(!m_cmbKdfMem.Sorted);
            m_cmbKdfMem.Items.Add("B");
            m_cmbKdfMem.Items.Add("KB");
            m_cmbKdfMem.Items.Add("MB");
            m_cmbKdfMem.Items.Add("GB");

            m_numKdfPar.Minimum = uint.MinValue;
            m_numKdfPar.Maximum = uint.MaxValue;

            SetKdfParameters(m_pwDatabase.KdfParameters);

            // m_lbMemProt.Items.Add(KPRes.Title, m_pwDatabase.MemoryProtection.ProtectTitle);
            // m_lbMemProt.Items.Add(KPRes.UserName, m_pwDatabase.MemoryProtection.ProtectUserName);
            // m_lbMemProt.Items.Add(KPRes.Password, m_pwDatabase.MemoryProtection.ProtectPassword);
            // m_lbMemProt.Items.Add(KPRes.Url, m_pwDatabase.MemoryProtection.ProtectUrl);
            // m_lbMemProt.Items.Add(KPRes.Notes, m_pwDatabase.MemoryProtection.ProtectNotes);

            // m_cbAutoEnableHiding.Checked = m_pwDatabase.MemoryProtection.AutoEnableVisualHiding;
            // m_cbAutoEnableHiding.Checked = false;

            if (m_pwDatabase.Compression == PwCompressionAlgorithm.None)
            {
                m_rbNone.Checked = true;
            }
            else if (m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
            {
                m_rbGZip.Checked = true;
            }
            else
            {
                Debug.Assert(false);
            }

            InitRecycleBinTab();
            InitAdvancedTab();

            m_bInitializing = false;
            EnableControlsEx();
            UIUtil.SetFocus(m_tbDbName, this);
        }
コード例 #28
0
ファイル: MruList.cs プロジェクト: mario2100/KeePass2.x
        private ToolStripMenuItem CreateMenuItem(MruMenuItemType t, string strText,
                                                 Image img, object oTag, bool bEnabled, uint uAccessKey)
        {
            string strItem = strText;

            if (uAccessKey >= 1)
            {
                NumberFormatInfo nfi = NumberFormatInfo.InvariantInfo;
                if (uAccessKey < 10)
                {
                    strItem = @"&" + uAccessKey.ToString(nfi) + " " + strItem;
                }
                else if (uAccessKey == 10)
                {
                    strItem = @"1&0 " + strItem;
                }
                else
                {
                    strItem = uAccessKey.ToString(nfi) + " " + strItem;
                }
            }

            ToolStripMenuItem tsmi = new ToolStripMenuItem(strItem);

            if (img != null)
            {
                tsmi.Image = img;
            }
            if (oTag != null)
            {
                tsmi.Tag = oTag;
            }

            IOConnectionInfo ioc = (oTag as IOConnectionInfo);

            if (m_bMarkOpened && (ioc != null) && (Program.MainForm != null))
            {
                foreach (PwDatabase pd in Program.MainForm.DocumentManager.GetOpenDatabases())
                {
                    if (pd.IOConnectionInfo.GetDisplayName().Equals(
                            ioc.GetDisplayName(), StrUtil.CaseIgnoreCmp))
                    {
                        // if(m_fItalic == null)
                        // {
                        //	Font f = tsi.Font;
                        //	if(f != null)
                        //		m_fItalic = FontUtil.CreateFont(f, FontStyle.Italic);
                        //	else { Debug.Assert(false); }
                        // }

                        // if(m_fItalic != null) tsmi.Font = m_fItalic;
                        // 153, 51, 153
                        tsmi.ForeColor = Color.FromArgb(64, 64, 255);
                        tsmi.Text     += " [" + KPRes.Opened + "]";
                        break;
                    }
                }
            }

            if (t == MruMenuItemType.Item)
            {
                tsmi.Click += this.ClickHandler;
            }
            else if (t == MruMenuItemType.Clear)
            {
                tsmi.Click += this.ClearHandler;
            }
            // t == MruMenuItemType.None needs no handler

            if (!bEnabled)
            {
                tsmi.Enabled = false;
            }

            return(tsmi);
        }
コード例 #29
0
ファイル: MainForm_Functions.cs プロジェクト: elitak/keepass
        private PwDatabase OpenDatabaseInternal(IOConnectionInfo ioc, CompositeKey cmpKey)
        {
            PerformSelfTest();

            ShowWarningsLogger swLogger = CreateShowWarningsLogger();
            swLogger.StartLogging(KPRes.OpeningDatabase, true);

            PwDocument ds = null;
            string strPathNrm = ioc.Path.Trim().ToLower();
            for(int iScan = 0; iScan < m_docMgr.Documents.Count; ++iScan)
            {
                if(m_docMgr.Documents[iScan].LockedIoc.Path.Trim().ToLower() == strPathNrm)
                    ds = m_docMgr.Documents[iScan];
                else if(m_docMgr.Documents[iScan].Database.IOConnectionInfo.Path == strPathNrm)
                    ds = m_docMgr.Documents[iScan];
            }

            PwDatabase pwDb;
            if(ds == null) pwDb = m_docMgr.CreateNewDocument(true).Database;
            else pwDb = ds.Database;

            try
            {
                pwDb.Open(ioc, cmpKey, swLogger);

            #if DEBUG
                byte[] pbDiskDirect = WinUtil.HashFile(ioc);
                Debug.Assert(MemUtil.ArraysEqual(pbDiskDirect, pwDb.HashOfFileOnDisk));
            #endif
            }
            catch(Exception ex)
            {
                MessageService.ShowLoadWarning(ioc.GetDisplayName(), ex);
                pwDb = null;
            }

            swLogger.EndLogging();

            if(pwDb == null)
            {
                if(ds == null) m_docMgr.CloseDatabase(m_docMgr.ActiveDatabase);
            }

            return pwDb;
        }
コード例 #30
0
 private void OnMenuDown(object sender, EventArgs e) {
     Thread uploadThread = new Thread(new ThreadStart(delegate() {
         string qiniuurl = QiniuCloud.Instance.GetQiniuUrl(KeePassQiniuConfig.Default.QiniuDataBase);
         IOConnectionInfo m_ioc = new IOConnectionInfo();
         m_ioc.Path = qiniuurl;
         string localSavePath = KeePassQiniuConfig.Default.DataDir + KeePassQiniuConfig.Default.QiniuDataBase;
         if(File.Exists(localSavePath)) {
             m_host.MainWindow.Invoke(new MethodInvoker(delegate() {
                 MessageService.ShowWarning("本地数据库存在", "数据库" + KeePassQiniuConfig.Default.QiniuDataBase + "已经存在!");
             }));
             return;
         }
         try {
             if(!IOConnection.FileExists(m_ioc, true)) {
                 throw new FileNotFoundException();
             } else {
                 byte[] bytes = IOConnection.ReadFile(m_ioc);
                 File.WriteAllBytes(localSavePath, bytes);
                 m_host.MainWindow.Invoke(new MethodInvoker(delegate() {
                     MessageService.ShowInfo("下载成功");
                     IOConnectionInfo local = new IOConnectionInfo();
                     local.Path = localSavePath;
                     m_host.MainWindow.OpenDatabase(local, null, true);
                 }));
             }
         } catch(Exception exTest) {
             string strError = exTest.Message;
             if(strError.Contains("404")) {
             } else {
                 if((exTest.InnerException != null) &&
                         !string.IsNullOrEmpty(exTest.InnerException.Message))
                     strError += MessageService.NewParagraph +
                                 exTest.InnerException.Message;
                 m_host.MainWindow.Invoke(new MethodInvoker(delegate() {
                     MessageService.ShowWarning(m_ioc.GetDisplayName(), strError);
                 }));
             }
         }
     }));
     uploadThread.Start();
 }
コード例 #31
0
ファイル: JavaFileStorage.cs プロジェクト: pythe/wristpass
 public IOConnectionInfo GetFilePath(IOConnectionInfo folderPath, string filename)
 {
     try
     {
         return IOConnectionInfo.FromPath(
         ListContents(folderPath).Where(desc => { return desc.DisplayName == filename; })
             .Single()
             .Path);
     }
     catch (Exception e)
     {
         throw new Exception("Error finding " + filename + " in " + folderPath.GetDisplayName(), e);
     }
 }