示例#1
0
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");
			return Copy(psToCopy.ReadString(), true, bIsEntryInfo, peEntryInfo,
				pwReferenceSource, IntPtr.Zero);
		}
示例#2
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(sInput);

			XmlNode xmlRoot = xmlDoc.DocumentElement;
			Debug.Assert(xmlRoot.Name == ElemRoot);

			Stack<PwGroup> vGroups = new Stack<PwGroup>();
			vGroups.Push(pwStorage.RootGroup);

			int nNodeCount = xmlRoot.ChildNodes.Count;
			for(int i = 0; i < nNodeCount; ++i)
			{
				XmlNode xmlChild = xmlRoot.ChildNodes[i];

				if(xmlChild.Name == ElemGroup)
					ReadGroup(xmlChild, vGroups, pwStorage);
				else { Debug.Assert(false); }

				if(slLogger != null)
					slLogger.SetProgress((uint)(((i + 1) * 100) / nNodeCount));
			}
		}
示例#3
0
		private static void ImportRecord(Node<BaseRecord> currentNode, PwGroup groupAddTo, PwDatabase pwStorage)
		{
			BaseRecord record = currentNode.AssociatedObject;

			if (record.GetType() == typeof(FolderRecord))
			{
				FolderRecord folderRecord = (FolderRecord)record;
				var folder = CreateFolder(groupAddTo, folderRecord);

				foreach (var node in currentNode.Nodes)
				{
					ImportRecord(node, folder, pwStorage);
				}
			}
			else if (record.GetType() == typeof(WebFormRecord))
			{
				WebFormRecord webForm = (WebFormRecord)record;
				CreateWebForm(groupAddTo, pwStorage, webForm);
			}
			else if (record.GetType() == typeof(BaseRecord))
			{
				//Trace.WriteLine(String.Format("Error. Can't import unknown record type: {0}", record.RawJson));
			}
			else if (record.GetType() == typeof(UnknownRecord))
			{
				//CreateUnknown(groupAddTo, pwStorage, record as UnknownRecord);
			}
		}
示例#4
0
文件: App.cs 项目: pythe/wristpass
                public void SetEntry(PwEntry e)
                {
                    KpDatabase = new PwDatabase();
                    KpDatabase.New(new IOConnectionInfo(), new CompositeKey());

                    KpDatabase.RootGroup.AddEntry(e, true);
                }
示例#5
0
        public void InitEx(bool bCreatingNew, PwDatabase pwDatabase)
        {
            m_bCreatingNew = bCreatingNew;

            Debug.Assert(pwDatabase != null); if(pwDatabase == null) throw new ArgumentNullException("pwDatabase");
            m_pwDatabase = pwDatabase;
        }
示例#6
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			StreamReader sr = new StreamReader(sInput, StrUtil.Utf8);
			string strDoc = sr.ReadToEnd();
			sr.Close();

			XmlDocument doc = new XmlDocument();
			doc.LoadXml(strDoc);

			XmlElement xmlRoot = doc.DocumentElement;
			Debug.Assert(xmlRoot.Name == ElemRoot);

			PwGroup pgRoot = pwStorage.RootGroup;

			foreach(XmlNode xmlChild in xmlRoot.ChildNodes)
			{
				if(xmlChild.Name == ElemGroup)
					ImportGroup(xmlChild, pgRoot, pwStorage, false);
				else if(xmlChild.Name == ElemRecycleBin)
					ImportGroup(xmlChild, pgRoot, pwStorage, true);
				else if(xmlChild.Name == ElemEntry)
					ImportEntry(xmlChild, pgRoot, pwStorage);
				else { Debug.Assert(false); }
			}
		}
 /// <summary>
 /// The function tries to merge possible updates from the deltaDB into
 /// the actual database. If there was made changes to the actualDB, then
 /// the function fires a event, which cause the KeePass UI to update and
 /// show the "save"-button.
 /// </summary>
 public void Import(object sender, SyncSource source)
 {
     Debug.Assert(source.DestinationDB != null && source.DestinationDB.RootGroup != null);
     //merge all updates in
     PwDatabase deltaDB = new PwDatabase();
     try
     {
         deltaDB.Open(IOConnectionInfo.FromPath(source.Location), source.Key, null);
     }
     catch (InvalidCompositeKeyException e)
     {
         Debug.WriteLine("Wrong key! exception was: " + e.Message);
         //brand this entry as a false one => red bg-color and "X" as group icon
         ShowErrorHighlight(source.DestinationDB, source.Uuid);
         if (Imported != null) Imported.Invoke(this, source.DestinationDB.RootGroup);
         return;
     }
     catch (Exception e)
     {
         Debug.WriteLine("Standard exception was thrown during deltaDB.Open(): " + e.Message);
         //maybe the process has not finished writing to our file, but the filewtcher fires our event
         //sourceEntryUuid we have to ignore it and wait for the next one.
         return;
     }
     HideErrorHighlight(source.DestinationDB, source.Uuid);
     MergeIn(source.DestinationDB, deltaDB);
     deltaDB.Close();
 }
示例#8
0
        protected static string GetValueFromDB(ref KeePassLib.PwDatabase pdb, string SearchString = "")
        {
            if (string.IsNullOrWhiteSpace(SearchString))
            {
                throw new ArgumentException("Search String Cannot be blank");
            }
            //byte[] keyBytes = System.Text.Encoding.Default.GetBytes(key); //new []{ System.Text.EncodingInfo}
            //Guid i = Guid.Parse(key);
            //var pwUuID = new PwUuid(i.ToByteArray());
            SearchParameters sp = new SearchParameters();

            sp.SearchInStringNames = true;
            sp.SearchString        = SearchString;
            PwObjectList <PwEntry> pwl = new PwObjectList <PwEntry>();

            pdb.RootGroup.SearchEntries(sp, pwl);
            string k = string.Empty;

            foreach (var entry in pwl)
            {
                foreach (var l in entry.Strings.ToList())
                {
                    if (l.Key == "Password")
                    {
                        k = l.Value.ReadString();
                    }
                }
            }
            return(k);
        }
示例#9
0
		private static void ImportEntry(XmlNode xmlNode, PwDatabase pwStorage,
			Dictionary<string, PwGroup> dGroups)
		{
			PwEntry pe = new PwEntry(true, true);
			string strGroup = string.Empty;

			foreach(XmlNode xmlChild in xmlNode)
			{
				string strInner = XmlUtil.SafeInnerText(xmlChild);

				if(xmlChild.Name == ElemCategory)
					strGroup = strInner;
				else if(xmlChild.Name == ElemTitle)
					pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
						pwStorage.MemoryProtection.ProtectTitle, strInner));
				else if(xmlChild.Name == ElemNotes)
					pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
						pwStorage.MemoryProtection.ProtectNotes, strInner));
			}

			PwGroup pg;
			dGroups.TryGetValue(strGroup, out pg);
			if(pg == null)
			{
				pg = new PwGroup(true, true);
				pg.Name = strGroup;
				dGroups[string.Empty].AddGroup(pg, true);
				dGroups[strGroup] = pg;
			}
			pg.AddEntry(pe, true);
		}
示例#10
0
		private static void ProcessCsvLine(string strLine, PwDatabase pwStorage)
		{
			List<string> list = ImportUtil.SplitCsvLine(strLine, ",");
			Debug.Assert(list.Count == 5);

			PwEntry pe = new PwEntry(true, true);
			pwStorage.RootGroup.AddEntry(pe, true);

			if(list.Count == 5)
			{
				pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectTitle,
					ProcessCsvWord(list[0])));
				pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUserName,
					ProcessCsvWord(list[1])));
				pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectPassword,
					ProcessCsvWord(list[2])));
				pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUrl,
					ProcessCsvWord(list[3])));
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectNotes,
					ProcessCsvWord(list[4])));
			}
			else throw new FormatException("Invalid field count!");
		}
示例#11
0
 public void CloseDatabase()
 {
     if (db != null) {
     db.Close ();
     db = null;
      }
 }
示例#12
0
        // public bool CopyHistory
        // {
        //    get { return m_bCopyHistory; }
        // }
        public void ApplyTo(PwEntry peNew, PwEntry pe, PwDatabase pd)
        {
            if((peNew == null) || (pe == null)) { Debug.Assert(false); return; }

            Debug.Assert(peNew.Strings.ReadSafe(PwDefs.UserNameField) ==
                pe.Strings.ReadSafe(PwDefs.UserNameField));
            Debug.Assert(peNew.Strings.ReadSafe(PwDefs.PasswordField) ==
                pe.Strings.ReadSafe(PwDefs.PasswordField));

            if(m_bAppendCopy && (pd != null))
            {
                string strTitle = peNew.Strings.ReadSafe(PwDefs.TitleField);
                peNew.Strings.Set(PwDefs.TitleField, new ProtectedString(
                    pd.MemoryProtection.ProtectTitle, strTitle + " - " +
                    KPRes.CopyOfItem));
            }

            if(m_bFieldRefs && (pd != null))
            {
                string strUser = @"{REF:U@I:" + pe.Uuid.ToHexString() + @"}";
                peNew.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                    pd.MemoryProtection.ProtectUserName, strUser));

                string strPw = @"{REF:P@I:" + pe.Uuid.ToHexString() + @"}";
                peNew.Strings.Set(PwDefs.PasswordField, new ProtectedString(
                    pd.MemoryProtection.ProtectPassword, strPw));
            }

            if(!m_bCopyHistory)
                peNew.History = new PwObjectList<PwEntry>();
        }
示例#13
0
        public void TestCreateSaveAndLoad_TestIdenticalFiles_kdb()
        {
            string filename = DefaultDirectory + "createsaveandload.kdb";
            IKp2aApp app = SetupAppWithDatabase(filename);
            string kdbxXml = DatabaseToXml(app);
            //save it and reload it
            Android.Util.Log.Debug("KP2A", "-- Save DB -- ");
            SaveDatabase(app);
            Android.Util.Log.Debug("KP2A", "-- Load DB -- ");

            PwDatabase pwImp = new PwDatabase();
            PwDatabase pwDatabase = app.GetDb().KpDatabase;
            pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
            pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
            pwImp.MasterKey = pwDatabase.MasterKey;

            IOConnectionInfo ioc = new IOConnectionInfo() {Path = filename};
            using (Stream s = app.GetFileStorage(ioc).OpenFileForRead(ioc))
            {
                app.GetDb().DatabaseFormat.PopulateDatabaseFromStream(pwImp, s, null);
            }
            string kdbxReloadedXml = DatabaseToXml(app);

            RemoveKdbLines(ref kdbxReloadedXml);
            RemoveKdbLines(ref kdbxXml);

            Assert.AreEqual(kdbxXml, kdbxReloadedXml);
        }
示例#14
0
		public static bool? Import(PwDatabase pwStorage, out bool bAppendedToRootOnly,
			Form fParent)
		{
			bAppendedToRootOnly = false;

			if(pwStorage == null) throw new ArgumentNullException("pwStorage");
			if(!pwStorage.IsOpen) return null;
			if(!AppPolicy.Try(AppPolicyId.Import)) return null;

			ExchangeDataForm dlgFmt = new ExchangeDataForm();
			dlgFmt.InitEx(false, pwStorage, pwStorage.RootGroup);

			if(dlgFmt.ShowDialog() == DialogResult.OK)
			{
				Debug.Assert(dlgFmt.ResultFormat != null);
				if(dlgFmt.ResultFormat == null)
				{
					MessageService.ShowWarning(KPRes.ImportFailed);
					return false;
				}

				bAppendedToRootOnly = dlgFmt.ResultFormat.ImportAppendsToRootGroupOnly;

				List<IOConnectionInfo> lConnections = new List<IOConnectionInfo>();
				foreach(string strSelFile in dlgFmt.ResultFiles)
					lConnections.Add(IOConnectionInfo.FromPath(strSelFile));

				return Import(pwStorage, dlgFmt.ResultFormat, lConnections.ToArray(),
					false, null, false, fParent);
			}

			return null;
		}
示例#15
0
		public static bool? Synchronize(PwDatabase pwStorage, IUIOperations uiOps,
			bool bOpenFromUrl, Form fParent)
		{
			if(pwStorage == null) throw new ArgumentNullException("pwStorage");
			if(!pwStorage.IsOpen) return null;
			if(!AppPolicy.Try(AppPolicyId.Import)) return null;

			List<IOConnectionInfo> vConnections = new List<IOConnectionInfo>();
			if(bOpenFromUrl == false)
			{
				OpenFileDialog ofd = UIUtil.CreateOpenFileDialog(KPRes.Synchronize,
					UIUtil.CreateFileTypeFilter(null, null, true), 1, null, true, true);

				if(ofd.ShowDialog() != DialogResult.OK) return null;

				foreach(string strSelFile in ofd.FileNames)
					vConnections.Add(IOConnectionInfo.FromPath(strSelFile));
			}
			else // Open URL
			{
				IOConnectionForm iocf = new IOConnectionForm();
				iocf.InitEx(false, new IOConnectionInfo(), true, true);

				if(iocf.ShowDialog() != DialogResult.OK) return null;

				vConnections.Add(iocf.IOConnectionInfo);
			}

			return Import(pwStorage, new KeePassKdb2x(), vConnections.ToArray(),
				true, uiOps, false, fParent);
		}
示例#16
0
        public void CreateAndSaveLocal()
        {
            IKp2aApp app = new TestKp2aApp();
            IOConnectionInfo ioc = new IOConnectionInfo {Path = DefaultFilename};

            File outputDir = new File(DefaultDirectory);
            outputDir.Mkdirs();
            File targetFile = new File(ioc.Path);
            if (targetFile.Exists())
                targetFile.Delete();

            bool createSuccesful = false;
            //create the task:
            CreateDb createDb = new CreateDb(app, Application.Context, ioc, new ActionOnFinish((success, message) =>
                { createSuccesful = success;
                    if (!success)
                        Android.Util.Log.Debug("KP2A_Test", message);
                }), false);
            //run it:

            createDb.Run();
            //check expectations:
            Assert.IsTrue(createSuccesful);
            Assert.IsNotNull(app.GetDb());
            Assert.IsNotNull(app.GetDb().KpDatabase);
            //the create task should create two groups:
            Assert.AreEqual(2, app.GetDb().KpDatabase.RootGroup.Groups.Count());

            //ensure the the database can be loaded from file:
            PwDatabase loadedDb = new PwDatabase();
            loadedDb.Open(ioc, new CompositeKey(), null, new KdbxDatabaseFormat(KdbxFormat.Default));

            //Check whether the databases are equal
            AssertDatabasesAreEqual(loadedDb, app.GetDb().KpDatabase);
        }
示例#17
0
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			Debug.Assert(psToCopy != null);
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");

			if(bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
				return false;

			string strData = SprEngine.Compile(psToCopy.ReadString(), false,
				peEntryInfo, pwReferenceSource, false, false);

			try
			{
				ClipboardUtil.Clear();

				DataObject doData = CreateProtectedDataObject(strData);
				Clipboard.SetDataObject(doData);

				m_pbDataHash32 = HashClipboard();
				m_strFormat = null;

				RaiseCopyEvent(bIsEntryInfo, strData);
			}
			catch(Exception) { Debug.Assert(false); return false; }

			if(peEntryInfo != null) peEntryInfo.Touch(false);

			// SprEngine.Compile might have modified the database
			Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

			return true;
		}
示例#18
0
    public static void Main(string[] args)
    {
        CompositeKey key = new CompositeKey();
        KcpPassword pw = new KcpPassword("12345");
        key.AddUserKey(pw);
        byte[] pwdata = pw.KeyData.ReadData();
        Console.WriteLine("PW data:");
        Console.WriteLine(string.Join(",", pwdata.Select(x => "0x" + x.ToString("x"))));
        byte[] keydata = key.GenerateKey32(pwdata, 6000).ReadData();
        Console.WriteLine("Key data:");
        Console.WriteLine(string.Join(",", keydata.Select(x => "0x" + x.ToString("x"))));

        PwDatabase db = new PwDatabase();
        db.MasterKey = key;
        KdbxFile kdbx = new KdbxFile(db);
        kdbx.Load(@"..\resources\test.kdbx", KdbxFormat.Default, null);

        var groups = db.RootGroup.GetGroups(true);
        Console.WriteLine("Group count: " + groups.UCount);
        var entries = db.RootGroup.GetEntries(true);
        Console.WriteLine("Entry count: " + entries.UCount);

        CompositeKey key2 = new CompositeKey();
        key2.AddUserKey(pw);
        KcpKeyFile keyfile = new KcpKeyFile(@"..\resources\keyfile.key");
        key2.AddUserKey(keyfile);
        byte[] keyfiledata = keyfile.KeyData.ReadData();
        Console.WriteLine("Key file data:");
        Console.WriteLine(string.Join(",", keyfiledata.Select(x => "0x" + x.ToString("x"))));
        Console.WriteLine("Composite Key data:");
        byte[] key2data = key2.GenerateKey32(keyfiledata, 6000).ReadData();
        Console.WriteLine(string.Join(",", key2data.Select(x => "0x" + x.ToString("x"))));
    }
示例#19
0
        public static bool Copy(string strToCopy, bool bIsEntryInfo,
            PwEntry peEntryInfo, PwDatabase pwReferenceSource)
        {
            Debug.Assert(strToCopy != null);
            if(strToCopy == null) throw new ArgumentNullException("strToCopy");

            if(bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
                return false;

            string strData = SprEngine.Compile(strToCopy, false, peEntryInfo,
                pwReferenceSource, false, false);

            try
            {
                Clipboard.Clear();

                DataObject doData = CreateProtectedDataObject(strData);
                Clipboard.SetDataObject(doData);

                m_pbDataHash32 = HashClipboard();
                m_strFormat = null;
            }
            catch(Exception) { Debug.Assert(false); return false; }

            return true;
        }
示例#20
0
 public Drawable GetIconDrawable(Resources res, PwDatabase db, PwIcon icon, PwUuid customIconId)
 {
     if (!customIconId.Equals(PwUuid.Zero)) {
         return GetIconDrawable (res, db, customIconId);
     }
     return GetIconDrawable (res, icon);
 }
示例#21
0
		public static bool Copy(string strToCopy, bool bSprCompile, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource, IntPtr hOwner)
		{
			if(strToCopy == null) throw new ArgumentNullException("strToCopy");

			if(bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
				return false;

			string strData = (bSprCompile ? SprEngine.Compile(strToCopy,
				new SprContext(peEntryInfo, pwReferenceSource,
				SprCompileFlags.All)) : strToCopy);

			try
			{
				if(!NativeLib.IsUnix()) // Windows
				{
					if(!OpenW(hOwner, true))
						throw new InvalidOperationException();

					bool bFailed = false;
					if(!AttachIgnoreFormatW()) bFailed = true;
					if(!SetDataW(null, strData, null)) bFailed = true;
					CloseW();

					if(bFailed) return false;
				}
				else if(NativeLib.GetPlatformID() == PlatformID.MacOSX)
					SetStringM(strData);
				else if(NativeLib.IsUnix())
					SetStringU(strData);
				// else // Managed
				// {
				//	Clear();
				//	DataObject doData = CreateProtectedDataObject(strData);
				//	Clipboard.SetDataObject(doData);
				// }
			}
			catch(Exception) { Debug.Assert(false); return false; }

			m_strFormat = null;

			byte[] pbUtf8 = StrUtil.Utf8.GetBytes(strData);
			SHA256Managed sha256 = new SHA256Managed();
			m_pbDataHash32 = sha256.ComputeHash(pbUtf8);

			RaiseCopyEvent(bIsEntryInfo, strData);

			if(peEntryInfo != null) peEntryInfo.Touch(false);

			// SprEngine.Compile might have modified the database
			MainForm mf = Program.MainForm;
			if((mf != null) && bSprCompile)
			{
				mf.RefreshEntriesList();
				mf.UpdateUI(false, null, false, null, false, null, false);
			}

			return true;
		}
示例#22
0
		public static string Compile(string strText, bool bIsAutoTypeSequence,
			PwEntry pwEntry, PwDatabase pwDatabase, bool bEscapeForAutoType,
			bool bEscapeQuotesForCommandLine)
		{
			SprContext ctx = new SprContext(pwEntry, pwDatabase, SprCompileFlags.All,
				bEscapeForAutoType, bEscapeQuotesForCommandLine);
			return Compile(strText, ctx);
		}
示例#23
0
 private PwEntry GetConfigEntry(PwDatabase db)
 {
     var kphe = new KeePassHttpExt();
     var root = db.RootGroup;
     var uuid = new PwUuid(kphe.KEEPASSHTTP_UUID);
     var entry = root.FindEntry(uuid, false);
     return entry;
 }
示例#24
0
        public AutoTypeCtx(string strSequence, PwEntry pe, PwDatabase pd)
        {
            if(strSequence == null) throw new ArgumentNullException("strSequence");

            m_strSeq = strSequence;
            m_pe = pe;
            m_pd = pd;
        }
示例#25
0
        public void InitEx(PwGroup pg, bool bCreatingNew, ImageList ilClientIcons,
			PwDatabase pwDatabase)
        {
            m_pwGroup = pg;
            m_bCreatingNew = bCreatingNew;
            m_ilClientIcons = ilClientIcons;
            m_pwDatabase = pwDatabase;
        }
示例#26
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		/// <param name="pwDataStore">The <c>PwDatabase</c> instance that the class
		/// will load file data into or use to create a KDB file. Must not be <c>null</c>.</param>
		/// <exception cref="System.ArgumentNullException">Thrown if the database
		/// reference is <c>null</c>.</exception>
		public KdbFile(PwDatabase pwDataStore, IStatusLogger slLogger)
		{
			Debug.Assert(pwDataStore != null);
			if(pwDataStore == null) throw new ArgumentNullException("pwDataStore");
			m_pwDatabase = pwDataStore;

			m_slLogger = slLogger;
		}
示例#27
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XmlSerializer xs = new XmlSerializer(typeof(HspFolder));
			HspFolder hspRoot = (HspFolder)xs.Deserialize(sInput);

			AddFolder(pwStorage.RootGroup, hspRoot, false);
		}
示例#28
0
		public void InitEx(ImageList ilIcons, uint uNumberOfStandardIcons,
			PwDatabase pwDatabase, uint uDefaultIcon, PwUuid pwCustomIconUuid)
		{
			m_ilIcons = ilIcons;
			m_uNumberOfStandardIcons = uNumberOfStandardIcons;
			m_pwDatabase = pwDatabase;
			m_uDefaultIcon = uDefaultIcon;
			m_pwDefaultCustomIcon = pwCustomIconUuid;
		}
示例#29
0
        public static IEnumerable<PwEntry> FindKeePassEntries(PwDatabase database,
            bool caseSensitive = false, 
            bool isSingle = false,
            string username = null, 
            string url = null, 
            string title = null, 
            string notes = null,  
            params string[] tags)
        {
            bool emptyUrl = string.IsNullOrWhiteSpace(url),
                 emptyTitle = string.IsNullOrWhiteSpace(title),
                 emptytUserName = string.IsNullOrWhiteSpace(username),
                 emptyNotes = string.IsNullOrWhiteSpace(notes),
                 emptyTags = tags == null || tags.Length == 0;

            if (emptyUrl && emptyTitle && emptyTags && emptytUserName && emptyNotes)
                throw new ArgumentException("At least one search parameter is required.");

            var entries = database.RootGroup.GetObjects(true, true);
            var results = new List<PwEntry>();
            foreach(PwEntry entry in entries)
            {
                var match = true;

                if (!emptyTitle)
                    match = Like(entry.Strings.ReadSafe("Title"), title, caseSensitive);

                if (!emptyUrl && match)
                    match = Like(entry.Strings.ReadSafe("URL"), url, caseSensitive);

                if (!emptytUserName && match)
                    match = Like(entry.Strings.ReadSafe("UserName"), username, caseSensitive);

                if (!emptyNotes && match)
                    match = Like(entry.Strings.ReadSafe("Notes"), notes, caseSensitive);

                if(!emptyTags && match)
                {
                    foreach(var tag in tags)
                    {
                        if(!entry.HasTag(tag))
                        {
                            match = false;
                            break;
                        }
                    }
                }

                if (match && isSingle)
                    return new PwEntry[] { entry };

                if(match)
                    results.Add(entry);
            }

            return results;
        }
示例#30
0
		public override void Import(PwDatabase pwStorage, Stream sInput,
			IStatusLogger slLogger)
		{
			XPathDocument xpDoc = new XPathDocument(sInput);
			XPathNavigator xpNav = xpDoc.CreateNavigator();

			ImportLogins(xpNav, pwStorage);
			ImportMemos(xpNav, pwStorage);
		}
        private static string GetValueFromDB(ref KeePassLib.PwDatabase pdb, string searchString = "")
        {
            if (string.IsNullOrWhiteSpace(searchString))
            {
                throw new ArgumentException("Search String Cannot be blank");
            }

            SearchProcessor processor = new SearchProcessor();

            processor.Database = pdb;
            //byte[] keyBytes = System.Text.Encoding.Default.GetBytes(key); //new []{ System.Text.EncodingInfo}
            //Guid i = Guid.Parse(key);
            //var pwUuID = new PwUuid(i.ToByteArray());

            //SearchParameters sp = new SearchParameters();
            //sp.SearchInStringNames = true;
            //sp.SearchString = searchString;
            //PwObjectList<PwEntry> pwl = new PwObjectList<PwEntry>();
            //pdb.RootGroup.SearchEntries(sp, pwl);

            PwObjectList <PwEntry> pwl = processor.GetListOfEntriesBySearchByString(searchString);

            System.Diagnostics.Debug.WriteLine($"Entries Found: {pwl.Count()}");
            string k = string.Empty;

            foreach (var entry in pwl.CloneShallowToList())
            {
                foreach (var l in entry.Strings.ToList())
                {
                    if (l.Key == "Password")
                    {
                        k = l.Value.ReadString();
                    }
                }
            }
            return(k);
        }
        public async void LoadKeePass(object sender, RoutedEventArgs e)
        {
            try
            {
                List <KeepassClass> PassList = new List <KeepassClass>();
                var           dbpath         = "";
                StorageFolder folder         = ApplicationData.Current.LocalFolder;
                StorageFile   file           = await folder.GetFileAsync((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePath"]);

                if (file != null)
                {
                    dbpath = file.Path;
                }
                var masterpw   = MasterPassword.Password;
                var ioConnInfo = new IOConnectionInfo {
                    Path = file.Path
                };
                var compKey = new CompositeKey();
                compKey.AddUserKey(new KcpPassword(MasterPassword.Password));
                var db = new KeePassLib.PwDatabase();

                /*  var kdbx = new KdbxFile(db);
                 * using (var fs = await file.OpenReadAsync())
                 * {
                 *    await Task.Run(() =>
                 *    {
                 *        kdbx.Load(file.Path, KdbxFormat.Default, null);
                 *    });
                 *
                 *   // return new KdbxDatabase(dbFile, db, dbFile.IdFromPath());
                 * }*/
                db.Open(ioConnInfo, compKey, null);
                var kpdata = from entry in db.RootGroup.GetEntries(true)
                             select new
                {
                    Group    = entry.ParentGroup.Name,
                    Title    = entry.Strings.ReadSafe("Title"),
                    Username = entry.Strings.ReadSafe("UserName"),
                    Password = entry.Strings.ReadSafe("Password"),
                    URL      = entry.Strings.ReadSafe("URL"),
                    Notes    = entry.Strings.ReadSafe("Notes")
                };
                foreach (var Item in kpdata)
                {
                    PassList.Add(new KeepassClass()
                    {
                        Title    = Item.Title,
                        Website  = Item.URL,
                        Password = Item.Password,
                        User     = Item.Username
                    });
                }
                PassListView.ItemsSource = PassList;
                db.Close();
            }
            catch
            {
                int duration = 3000;
                try
                {
                    TabViewPage.InAppNotificationMain.Show("An error occured", duration);
                }
                catch
                {
                    IncognitoTabView.InAppNotificationMain.Show("An error occured", duration);
                }
            }
        }
        private async void AddKeeButton_Click(object sender, RoutedEventArgs e)
        {
            List <KeepassClass> PassList = new List <KeepassClass>();
            var           dbpath         = "";
            StorageFolder folder         = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile   file           = await folder.GetFileAsync((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePath"]);

            if (file != null)
            {
                dbpath = file.Path;
            }
            var masterpw   = MasterPassword.Password;
            var ioConnInfo = new IOConnectionInfo {
                Path = file.Path
            };
            var compKey = new CompositeKey();

            compKey.AddUserKey(new KcpPassword(MasterPassword.Password));
            var db = new KeePassLib.PwDatabase();

            /*  var kdbx = new KdbxFile(db);
             * using (var fs = await file.OpenReadAsync())
             * {
             *    await Task.Run(() =>
             *    {
             *        kdbx.Load(file.Path, KdbxFormat.Default, null);
             *    });
             *
             *   // return new KdbxDatabase(dbFile, db, dbFile.IdFromPath());
             * }*/
            db.Open(ioConnInfo, compKey, null);
            var pwEntry = new PwEntry(true, true);

            if (!string.IsNullOrEmpty(Title.Text))
            {
                pwEntry.Strings.Set(PwDefs.TitleField, new ProtectedString(true, Title.Text));
            }

            if (!string.IsNullOrEmpty(User.Text))
            {
                pwEntry.Strings.Set(PwDefs.UserNameField, new ProtectedString(true, User.Text));
            }

            if (!string.IsNullOrEmpty(Password.Text))
            {
                pwEntry.Strings.Set(PwDefs.PasswordField, new ProtectedString(true, Password.Text));
            }

            if (!string.IsNullOrEmpty(Notes.Text))
            {
                pwEntry.Strings.Set(PwDefs.NotesField, new ProtectedString(true, Notes.Text));
            }

            if (!string.IsNullOrEmpty(Url.Text))
            {
                pwEntry.Strings.Set(PwDefs.UrlField, new ProtectedString(true, Url.Text));
            }
            // db.RootGroup.AddEntry(pwEntry, true);
            db.RootGroup.Entries.Add(pwEntry);
            db.Modified = true;
            // db.Save();
            var stream = await file.OpenStreamForWriteAsync();

            var kdbx = new KdbxFile(db);

            kdbx.Save(stream, null, KdbxFormat.Default, null);
            db.Close();
            int duration = 3000;

            try {
                TabViewPage.InAppNotificationMain.Show("Saved, please refresh list", duration);
            }
            catch
            {
                IncognitoTabView.InAppNotificationMain.Show("Saved, please refresh list", duration);
            }
        }
        private async void LoadKeeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List <KeepassClass> PassList = new List <KeepassClass>();
                var dbpath = "";
                var picker = new Windows.Storage.Pickers.FileOpenPicker();
                picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
                picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                picker.FileTypeFilter.Add(".kdb");
                picker.FileTypeFilter.Add(".kdbx");


                Windows.Storage.StorageFile File = await picker.PickSingleFileAsync();

                StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile   file   = await File.CopyAsync(folder);

                if (file != null)
                {
                    dbpath = file.Path;
                }
                var masterpw   = MasterPassword.Password;
                var ioConnInfo = new IOConnectionInfo {
                    Path = file.Path
                };
                var compKey = new CompositeKey();
                compKey.AddUserKey(new KcpPassword(MasterPassword.Password));
                var db = new KeePassLib.PwDatabase();
                Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePathBool"] = true;
                Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePath"]     = file.Name;

                /*  var kdbx = new KdbxFile(db);
                 * using (var fs = await file.OpenReadAsync())
                 * {
                 *    await Task.Run(() =>
                 *    {
                 *        kdbx.Load(file.Path, KdbxFormat.Default, null);
                 *    });
                 *
                 *   // return new KdbxDatabase(dbFile, db, dbFile.IdFromPath());
                 * }*/
                db.Open(ioConnInfo, compKey, null);
                var kpdata = from entry in db.RootGroup.GetEntries(true)
                             select new
                {
                    Group    = entry.ParentGroup.Name,
                    Title    = entry.Strings.ReadSafe("Title"),
                    Username = entry.Strings.ReadSafe("UserName"),
                    Password = entry.Strings.ReadSafe("Password"),
                    URL      = entry.Strings.ReadSafe("URL"),
                    Notes    = entry.Strings.ReadSafe("Notes")
                };
                foreach (var Item in kpdata)
                {
                    PassList.Add(new KeepassClass()
                    {
                        Title    = Item.Title,
                        Website  = Item.URL,
                        Password = Item.Password,
                        User     = Item.Username
                    });
                }
                PassListView.ItemsSource  = PassList;
                LoadKeeButton.Visibility  = Visibility.Collapsed;
                AddKeeButton.Visibility   = Visibility.Visible;
                EnterKeeButton.Visibility = Visibility.Visible;
                db.Close();
            }
            catch
            {
                int duration = 3000;
                try {
                    TabViewPage.InAppNotificationMain.Show("Wrong password!", duration);
                }
                catch
                {
                    IncognitoTabView.InAppNotificationMain.Show("Wrong password!", duration);
                }
                Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePathBool"] = false;
                Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePath"]     = null;
            }
        }
示例#35
0
        /// <summary>
        /// Synchronize the current database with another one.
        /// </summary>
        /// <param name="pwSource">Input database to synchronize with. This input
        /// database is used to update the current one, but is not modified! You
        /// must copy the current object if you want a second instance of the
        /// synchronized database. The input database must not be seen as valid
        /// database any more after calling <c>Synchronize</c>.</param>
        /// <param name="mm">Merge method.</param>
        public void MergeIn(PwDatabase pwSource, PwMergeMethod mm)
        {
            if (mm == PwMergeMethod.CreateNewUuids)
            {
                pwSource.RootGroup.CreateNewItemUuids(true, true, true);
            }

            GroupHandler gh = delegate(PwGroup pg)
            {
                if (pg == pwSource.m_pgRootGroup)
                {
                    return(true);
                }

                PwGroup pgLocal = m_pgRootGroup.FindGroup(pg.Uuid, true);
                if (pgLocal == null)
                {
                    PwGroup pgSourceParent = pg.ParentGroup;
                    PwGroup pgLocalContainer;
                    if (pgSourceParent == pwSource.m_pgRootGroup)
                    {
                        pgLocalContainer = m_pgRootGroup;
                    }
                    else
                    {
                        pgLocalContainer = m_pgRootGroup.FindGroup(pgSourceParent.Uuid, true);
                    }
                    Debug.Assert(pgLocalContainer != null);

                    PwGroup pgNew = new PwGroup();
                    pgNew.Uuid = pg.Uuid;
                    pgNew.AssignProperties(pg, false);
                    pgLocalContainer.AddGroup(pgNew, true);
                }
                else                 // pgLocal != null
                {
                    Debug.Assert(mm != PwMergeMethod.CreateNewUuids);

                    if (mm == PwMergeMethod.OverwriteExisting)
                    {
                        pgLocal.AssignProperties(pg, false);
                    }
                    else if ((mm == PwMergeMethod.OverwriteIfNewer) ||
                             (mm == PwMergeMethod.Synchronize))
                    {
                        pgLocal.AssignProperties(pg, true);
                    }
                    // else if(mm == PwMergeMethod.KeepExisting) ...
                }

                return(true);
            };

            EntryHandler eh = delegate(PwEntry pe)
            {
                PwEntry peLocal = m_pgRootGroup.FindEntry(pe.Uuid, true);
                if (peLocal == null)
                {
                    PwGroup pgSourceParent = pe.ParentGroup;
                    PwGroup pgLocalContainer;
                    if (pgSourceParent == pwSource.m_pgRootGroup)
                    {
                        pgLocalContainer = m_pgRootGroup;
                    }
                    else
                    {
                        pgLocalContainer = m_pgRootGroup.FindGroup(pgSourceParent.Uuid, true);
                    }
                    Debug.Assert(pgLocalContainer != null);

                    PwEntry peNew = new PwEntry(false, false);
                    peNew.Uuid = pe.Uuid;
                    peNew.AssignProperties(pe, false, true);
                    pgLocalContainer.AddEntry(peNew, true);
                }
                else                 // peLocal == null
                {
                    Debug.Assert(mm != PwMergeMethod.CreateNewUuids);

                    if (mm == PwMergeMethod.OverwriteExisting)
                    {
                        peLocal.AssignProperties(pe, false, true);
                    }
                    else if ((mm == PwMergeMethod.OverwriteIfNewer) ||
                             (mm == PwMergeMethod.Synchronize))
                    {
                        peLocal.AssignProperties(pe, true, true);
                    }
                    // else if(mm == PwMergeMethod.KeepExisting) ...
                }

                return(true);
            };

            if (!pwSource.RootGroup.TraverseTree(TraversalMethod.PreOrder, gh, eh))
            {
                throw new InvalidOperationException();
            }

            if (mm == PwMergeMethod.Synchronize)
            {
                ApplyDeletions(pwSource.m_vDeletedObjects, true);
                ApplyDeletions(m_vDeletedObjects, false);
            }
        }
示例#36
-1
		private static void ProcessCsvLine(string strLine, PwDatabase pwStorage)
		{
			List<string> list = ImportUtil.SplitCsvLine(strLine, ",");
			Debug.Assert(list.Count == 6);

			PwEntry pe = new PwEntry(true, true);
			pwStorage.RootGroup.AddEntry(pe, true);

			if(list.Count == 6)
			{
				pe.Strings.Set(PwDefs.TitleField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectTitle,
					ParseCsvWord(list[0], false)));
				pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUserName,
					ParseCsvWord(list[1], false)));
				pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectPassword,
					ParseCsvWord(list[2], false)));
				pe.Strings.Set(PwDefs.UrlField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectUrl,
					ParseCsvWord(list[3], false)));
				pe.Strings.Set(PwDefs.NotesField, new ProtectedString(
					pwStorage.MemoryProtection.ProtectNotes,
					ParseCsvWord(list[4], true)));

				DateTime dt;
				if(DateTime.TryParse(ParseCsvWord(list[5], false), out dt))
				{
					pe.CreationTime = pe.LastAccessTime = pe.LastModificationTime = dt;
				}
				else { Debug.Assert(false); }
			}
			else throw new FormatException("Invalid field count!");
		}