private bool ReturnFileOrStartFileChooser(string filename) { int lastSlashPos = filename.LastIndexOf('/'); int lastDotPos = filename.LastIndexOf('.'); if (lastSlashPos >= lastDotPos) //no dot after last slash or == in case neither / nor . { //looks like a folder. return(StartFileChooser(filename)); } //looks like a file IocSelected(IOConnectionInfo.FromPath(filename)); return(true); }
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); } }
private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData) { Debug.Assert(strFile != null); if (strFile == null) { throw new ArgumentNullException("strFile"); } Debug.Assert(pbKeyData != null); if (pbKeyData == null) { throw new ArgumentNullException("pbKeyData"); } IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); Stream sOut = IOConnection.OpenWrite(ioc); XmlTextWriter xtw = new XmlTextWriter(sOut, StrUtil.Utf8); xtw.WriteStartDocument(); xtw.WriteWhitespace("\r\n"); xtw.WriteStartElement(RootElementName); // KeyFile xtw.WriteWhitespace("\r\n\t"); xtw.WriteStartElement(MetaElementName); // Meta xtw.WriteWhitespace("\r\n\t\t"); xtw.WriteStartElement(VersionElementName); // Version xtw.WriteString("1.00"); xtw.WriteEndElement(); // End Version xtw.WriteWhitespace("\r\n\t"); xtw.WriteEndElement(); // End Meta xtw.WriteWhitespace("\r\n\t"); xtw.WriteStartElement(KeyElementName); // Key xtw.WriteWhitespace("\r\n\t\t"); xtw.WriteStartElement(KeyDataElementName); // Data xtw.WriteString(Convert.ToBase64String(pbKeyData)); xtw.WriteEndElement(); // End Data xtw.WriteWhitespace("\r\n\t"); xtw.WriteEndElement(); // End Key xtw.WriteWhitespace("\r\n"); xtw.WriteEndElement(); // RootElementName xtw.WriteWhitespace("\r\n"); xtw.WriteEndDocument(); // End KeyFile xtw.Close(); sOut.Close(); }
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)); }
public override void InitializeEntry(PwEntry entry) { base.InitializeEntry(entry); if (!entry.Strings.Exists(strVisible)) { entry.Strings.Set(strVisible, new ProtectedString(false, "true")); } if (!entry.Strings.Exists(strEnabled)) { entry.Strings.Set(strEnabled, new ProtectedString(false, "true")); } var autoExecItem = KeeAutoExecExt.MakeAutoExecItem(App.Kp2a.CurrentDb.KpDatabase, entry, 0); IOConnectionInfo ioc; if (!KeeAutoExecExt.TryGetDatabaseIoc(autoExecItem, out ioc)) { ioc = IOConnectionInfo.FromPath(entry.Strings.ReadSafe(PwDefs.UrlField)); } string path = ioc.Path; try { var filestorage = App.Kp2a.GetFileStorage(ioc); if (filestorage != null) { path = filestorage.IocToPath(ioc); } } catch (NoFileStorageFoundException) { } entry.Strings.Set(strUiDatabaseFile, new ProtectedString(false, path)); entry.Strings.Set(strUiKeyFile, new ProtectedString(false, entry.Strings.ReadSafe(PwDefs.UserNameField))); var devices = KeeAutoExecExt.GetIfDevice(KeeAutoExecExt.MakeAutoExecItem(App.Kp2a.CurrentDb.KpDatabase, entry, 0)); //make sure user can enable/disable on this device explicitly: if (!devices.ContainsKey(KeeAutoExecExt.ThisDeviceId)) { devices[KeeAutoExecExt.ThisDeviceId] = false; } foreach (var ifDevice in devices) { entry.Strings.Set(strUiIfDevice + ifDevice.Key, new ProtectedString(false, ifDevice.Value.ToString())); } }
private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData) { Debug.Assert(strFile != null); if (strFile == null) { throw new ArgumentNullException("strFile"); } #endif Debug.Assert(pbKeyData != null); if (pbKeyData == null) { throw new ArgumentNullException("pbKeyData"); } #if ModernKeePassLib var fileContents = new byte[0]; var ioc = IOConnectionInfo.FromByteArray(fileContents); #else IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); #endif using (Stream s = IOConnection.OpenWrite(ioc)) { using (XmlWriter xw = XmlUtilEx.CreateXmlWriter(s)) { xw.WriteStartDocument(); xw.WriteStartElement(RootElementName); // <KeyFile> xw.WriteStartElement(MetaElementName); // <Meta> xw.WriteStartElement(VersionElementName); // <Version> xw.WriteString("1.00"); xw.WriteEndElement(); // </Version> xw.WriteEndElement(); // </Meta> xw.WriteStartElement(KeyElementName); // <Key> xw.WriteStartElement(KeyDataElementName); // <Data> xw.WriteString(Convert.ToBase64String(pbKeyData)); xw.WriteEndElement(); // </Data> xw.WriteEndElement(); // </Key> xw.WriteEndElement(); // </KeyFile> xw.WriteEndDocument(); } #if ModernKeePassLib return(((MemoryStream)s).ToArray()); #endif } }
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 (UIUtil.ShowDialogNotValue(dlgFmt, DialogResult.OK)) { return(null); } Debug.Assert(dlgFmt.ResultFormat != null); if (dlgFmt.ResultFormat == null) { MessageService.ShowWarning(KPRes.ImportFailed); UIUtil.DestroyForm(dlgFmt); return(false); } bAppendedToRootOnly = dlgFmt.ResultFormat.ImportAppendsToRootGroupOnly; FileFormatProvider ffp = dlgFmt.ResultFormat; List <IOConnectionInfo> lConnections = new List <IOConnectionInfo>(); foreach (string strSelFile in dlgFmt.ResultFiles) { lConnections.Add(IOConnectionInfo.FromPath(strSelFile)); } UIUtil.DestroyForm(dlgFmt); return(Import(pwStorage, ffp, lConnections.ToArray(), false, null, false, fParent)); }
public void ShouldExportToTargets() { //we change the password which is used to encrypt the delta container so we can later access the delta container //more easily. PwEntry mrX = TestHelper.GetUserRootNodeFor(m_database, 0); //the first autoExport only checks if there is a delta container allready and if not it will export one //in our case there should be no existing container so a new one will be created. var exportFolder = m_database.GetExportGroup(); Assert.IsTrue(0 == exportFolder.Groups.UCount); string exportPath = GetTestPath(); m_syncManager.AddExportPath(exportPath); var exportGroup = exportFolder.Groups.GetAt(0); exportGroup.AddEntry(mrX.CreateProxyNode(), true); string exportFile = exportPath + SyncSource.FileNameFor(mrX) + SyncExporter.FileExtension; Assert.IsFalse(File.Exists(exportFile)); m_syncManager.RefeshSourcesList(); m_syncManager.Export(); mrX = TestHelper.GetUserRootNodeFor(m_database, 0); Assert.AreEqual("mrX", mrX.Strings.ReadSafe(KeeShare.KeeShare.TitleField)); Assert.IsTrue(File.Exists(exportFile)); //now we open the creted delta container and verify the contend PwDatabase deltaDB = new PwDatabase(); Assert.DoesNotThrow(delegate { deltaDB.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null); }); Assert.AreEqual(5, deltaDB.RootGroup.GetEntries(true).UCount); Assert.AreEqual(3, deltaDB.RootGroup.Entries.UCount); Assert.AreEqual("grp1", deltaDB.RootGroup.Groups.GetAt(0).Name); Assert.AreEqual(2, deltaDB.RootGroup.Groups.GetAt(0).Entries.UCount); //now we will test in detail if there are only the expected entries in the created delta container Assert.AreEqual(Uuid1, deltaDB.RootGroup.Entries.GetAt(0).Uuid); Assert.AreEqual(Uuid3, deltaDB.RootGroup.Entries.GetAt(2).Uuid); Assert.AreEqual(Uuid6, deltaDB.RootGroup.Entries.GetAt(1).Uuid); Assert.AreEqual(Uuid4, deltaDB.RootGroup.Groups.GetAt(0).Entries.GetAt(0).Uuid); Assert.AreEqual(Uuid5, deltaDB.RootGroup.Groups.GetAt(0).Entries.GetAt(1).Uuid); Assert.AreEqual("normalEntry1", deltaDB.RootGroup.Entries.GetAt(0).GetTitle()); deltaDB.Close(); }
public static KeePassWrapper OpenWithPassword(string path, string password) { var wrapper = new KeePassWrapper { Path = path, Database = new PwDatabase() }; var io = IOConnectionInfo.FromPath(path); var masterpass = new KcpPassword(password); var compositeKey = new CompositeKey(); compositeKey.AddUserKey(masterpass); wrapper.Database.Open(io, compositeKey, new NullStatusLogger()); return(wrapper); }
public static void ProcessGlobalMessage(int nId, MainForm mf) { if (mf == null) { throw new ArgumentNullException("mf"); } IpcParamEx ipcMsg = LoadIpcInfoFile(nId); if (ipcMsg == null) { return; } if (ipcMsg.Message == CmdOpenDatabase) { mf.UIBlockAutoUnlock(true); mf.EnsureVisibleForegroundWindow(true, true); mf.UIBlockAutoUnlock(false); // Don't try to open another database while a dialog // is displayed (3489098) if (GlobalWindowManager.WindowCount > 0) { return; } string[] vArgs = CommandLineArgs.SafeDeserialize(ipcMsg.Param0); if (vArgs == null) { Debug.Assert(false); return; } CommandLineArgs args = new CommandLineArgs(vArgs); Program.CommandLineArgs.CopyFrom(args); mf.OpenDatabase(IOConnectionInfo.FromPath(args.FileName), KeyUtil.KeyFromCommandLine(Program.CommandLineArgs), true); } else if (ipcMsg.Message == CmdOpenEntryUrl) { OpenEntryUrl(ipcMsg, mf); } else { Debug.Assert(false); } }
public SyncSource(PwEntry entry, PwDatabase dest) { m_sourceEntryUuid = entry.Uuid; string location = entry.Strings.ReadSafe(KeeShare.SourcePathField); if (IOConnectionInfo.FromPath(location).CanProbablyAccess()) { m_location = location; } Key = CreateKeyFor(entry); m_destinationDB = dest; m_watcher.Changed += new FileSystemEventHandler(OnChanged); m_watcher.Path = Path.GetDirectoryName(m_location); m_watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime; m_watcher.Filter = Path.GetFileName(m_location); }
void DownloadDatabase(object sender, EventArgs e) { try { var file = DatabaseList.DownloadDatabase(Api); if (file != null) { var ioConnection = IOConnectionInfo.FromPath(file.FullName); _host.MainWindow.OpenDatabase(ioConnection, null, false); } } catch (Exception ex) { ShowNotification(ex.Message); } }
private static string ChangePathRelAbsStr(string strPath, bool bMakeAbsolute) { if (strPath == null) { Debug.Assert(false); return(string.Empty); } if (strPath.Length == 0) { return(strPath); } IOConnectionInfo ioc = IOConnectionInfo.FromPath(strPath); ChangePathRelAbs(ioc, bMakeAbsolute); return(ioc.Path); }
public void SaveDatabase(string filePath) { if (db == null) { return; } if (!db.IsOpen) { return; } IOConnectionInfo ioc = IOConnectionInfo.FromPath(filePath); db.SaveAs(ioc, true, new DefaultKeePassLogger()); }
private static bool SaveConfigFileEx(AppConfigEx tConfig, string strFilePath, bool bRemoveConfigPref) { tConfig.OnSavePre(); // Temporarily remove user file preference (restore after saving) bool bConfigPref = tConfig.Meta.PreferUserConfiguration; if (bRemoveConfigPref) { tConfig.Meta.PreferUserConfiguration = false; } bool bResult = true; try { Debug.Assert(!string.IsNullOrEmpty(strFilePath)); IOConnectionInfo iocPath = IOConnectionInfo.FromPath(strFilePath); using (FileTransactionEx ft = new FileTransactionEx(iocPath, Program.Config.Application.UseTransactedConfigWrites)) { using (Stream s = ft.OpenWrite()) { using (XmlWriter xw = XmlUtilEx.CreateXmlWriter(s)) { XmlSerializerEx xs = new XmlSerializerEx(typeof(AppConfigEx)); xs.Serialize(xw, tConfig); } } ft.CommitWrite(); } } catch (Exception) { Debug.Assert(false); bResult = false; } if (bRemoveConfigPref) { tConfig.Meta.PreferUserConfiguration = bConfigPref; } AssertConfigPref(tConfig); tConfig.OnSavePost(); return(bResult); }
public IKeePassService Open() { //TODO add support for composite database keys if (KeePassPasswordProvider.RetrievePassword() == null) { throw new ArgumentNullException("password", "Password provided by IKeePassPasswordValueProvider is not set. Please register Password before calling Open()."); } var io = IOConnectionInfo.FromPath(Configuration.Path); var masterpass = new KcpPassword(KeePassPasswordProvider.RetrievePassword().ConvertToUnsecureString()); var compositeKey = new CompositeKey(); compositeKey.AddUserKey(masterpass); _database = new PwDatabase(); _database.Open(io, compositeKey, new NullStatusLogger()); return(this); }
private static IOConnectionInfo IOFromParameters(string strPath, string strUser, string strPassword) { IOConnectionInfo iocBase = IOConnectionInfo.FromPath(strPath); if (!string.IsNullOrEmpty(strUser)) { iocBase.UserName = strUser; } if (!string.IsNullOrEmpty(strPassword)) { iocBase.Password = strPassword; } if (!string.IsNullOrEmpty(iocBase.UserName)) { iocBase.CredSaveMode = IOCredSaveMode.UserNameOnly; } if (!string.IsNullOrEmpty(iocBase.Password)) { iocBase.CredSaveMode = IOCredSaveMode.SaveCred; } if (string.IsNullOrEmpty(iocBase.UserName) && string.IsNullOrEmpty(iocBase.Password)) { MruList mru = Program.MainForm.FileMruList; for (uint u = 0; u < mru.ItemCount; ++u) { IOConnectionInfo iocMru = (mru.GetItem(u).Value as IOConnectionInfo); if (iocMru == null) { Debug.Assert(false); continue; } if (iocMru.Path == iocBase.Path) { iocBase = iocMru.CloneDeep(); break; } } } return(MainForm.CompleteConnectionInfo(iocBase, false, true, true, false)); }
private static string DownloadString(string url) { var ioc = IOConnectionInfo.FromPath(url); using (var s = IOConnection.OpenRead(ioc)) { if (s == null) { throw new InvalidOperationException(); } using (var ms = new MemoryStream()) { MemUtil.CopyStream(s, ms); return(StrUtil.Utf8.GetString(ms.ToArray())); } } }
public void ShouldHandleCyclesOfNodesInImportAndExport() { var exportPath = GetTestPath(); m_syncManager.AddExportPath(exportPath); var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX"); m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrX.CreateProxyNode(), true); var existingEntry = new PwEntry(true, true); existingEntry.SetTitle("Entry Version 1"); m_database.RootGroup.AddEntry(existingEntry, true); m_database.RootGroup.AddEntry(userMrX.CreateProxyNode(), true); m_treeManager.CorrectStructure(); string exportFile = exportPath + SyncSource.FileNameFor(userMrX) + SyncExporter.FileExtension; Assert.IsFalse(File.Exists(exportFile)); m_syncManager.Export(); var deltaDBInitial = new PwDatabase(); deltaDBInitial.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null); Assert.AreEqual(1, deltaDBInitial.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 1")); foreach (var entry in deltaDBInitial.RootGroup.GetEntries(true)) { entry.SetTitle("Changed"); } deltaDBInitial.Save(null); deltaDBInitial.Close(); m_syncManager.AddImportPath(exportFile); m_database.GetImportGroup().Groups.GetAt(0).Entries.GetAt(0).SetPassword(userMrX.Strings.ReadSafe(KeeShare.KeeShare.PasswordField)); m_syncManager.RefeshSourcesList(); // Node normalEntry6 is within the user home and is relocated on export which changes the parent node - during import, the parents of // not "officially" relocated nodes is checked and an assertion is thrown Assert.AreEqual(0, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Changed")); }
/// <summary> /// Merges the KeePass database at the provided path with the current database /// </summary> /// <param name="databaseConfig">Configuration of the database to merge the KeePass database with</param> /// <param name="tempDatabasePath">Path to the KeePass database to merge with the currently open database</param> /// <returns>True if successful, false if failed to merge</returns> public static bool MergeDatabases(Configuration databaseConfig, string tempDatabasePath) { var connectionInfo = IOConnectionInfo.FromPath(tempDatabasePath); var formatter = KoenZomersKeePassOneDriveSyncExt.Host.FileFormatPool.Find("KeePass KDBX (2.x)"); // Temporarily switch off syncing for this database to avoid the import operation, which causes a save, to create and endless loop databaseConfig.SyncingEnabled = false; // Import the current database with the downloaded database. Import causes a one way sync, syncing would try to update both ends which won't work for OneDrive. var importSuccessful = ImportUtil.Import(databaseConfig.KeePassDatabase, formatter, new[] { connectionInfo }, true, KoenZomersKeePassOneDriveSyncExt.Host.MainWindow, false, KoenZomersKeePassOneDriveSyncExt.Host.MainWindow); // Enable syncing of this database again databaseConfig.SyncingEnabled = true; // Remove the temporary database from the Most Recently Used (MRU) list in KeePass as its added automatically on the import action KoenZomersKeePassOneDriveSyncExt.Host.MainWindow.FileMruList.RemoveItem(tempDatabasePath); return(importSuccessful.GetValueOrDefault(false)); }
internal static bool CanLoad(string strFilePath) { if (string.IsNullOrEmpty(strFilePath)) { Debug.Assert(false); return(false); } try { IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath); using (Stream s = IOConnection.OpenRead(ioc)) { return(Load(s) != null); } } catch (Exception) { } return(false); }
public void ShouldNotImportDatabasesWithDifferentUsers() { var exportPath = GetTestPath(); m_syncManager.AddExportPath(exportPath); var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX"); var userMrY = TestHelper.GetUserRootNodeByNameFor(m_database, "mrY"); m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrY.CreateProxyNode(), true); var existingEntry = new PwEntry(true, true); existingEntry.SetTitle("Entry Version 1"); m_database.RootGroup.AddEntry(existingEntry, true); m_database.RootGroup.AddEntry(userMrY.CreateProxyNode(), true); m_treeManager.CorrectStructure(); string exportFile = exportPath + SyncSource.FileNameFor(userMrY) + SyncExporter.FileExtension; Assert.IsFalse(File.Exists(exportFile)); m_syncManager.Export(); existingEntry.SetTitle("Entry Version 2"); var deltaDBInitial = new PwDatabase(); deltaDBInitial.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null); Assert.AreEqual(0, deltaDBInitial.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 2")); Assert.AreEqual(1, deltaDBInitial.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 1")); deltaDBInitial.Close(); m_syncManager.AddImportPath(exportFile); m_database.GetImportGroup().Groups.GetAt(0).Entries.GetAt(0).SetPassword("InvalidPassword"); m_syncManager.RefeshSourcesList(); Assert.AreEqual(1, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 2")); Assert.AreEqual(0, m_database.RootGroup.GetEntries(true).Count(e => e.GetTitle() == "Entry Version 1")); }
public static void ImportInto(PwDatabase pwStorage, out bool bAppendedToRootOnly) { bAppendedToRootOnly = false; if (pwStorage == null) { throw new ArgumentNullException("pwStorage"); } if (!pwStorage.IsOpen) { return; } if (!AppPolicy.Try(AppPolicyId.Import)) { return; } 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; } bAppendedToRootOnly = dlgFmt.ResultFormat.ImportAppendsToRootGroupOnly; List <IOConnectionInfo> lConnections = new List <IOConnectionInfo>(); foreach (string strSelFile in dlgFmt.ResultFiles) { lConnections.Add(IOConnectionInfo.FromPath(strSelFile)); } PerformImport(pwStorage, dlgFmt.ResultFormat, lConnections.ToArray(), false, null, false); } }
// Start of modification by B.L //Shamir Synchronize public static bool?ShamirSynchronize(PwDatabase pwStorage, IUIOperations uiOps, bool bOpenFromUrl, Form fParent, List <string> paths) { 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) { foreach (string s in paths) { vConnections.Add(IOConnectionInfo.FromPath(s)); } } else // Open URL { IOConnectionForm iocf = new IOConnectionForm(); iocf.InitEx(false, null, true, true); if (UIUtil.ShowDialogNotValue(iocf, DialogResult.OK)) { return(null); } vConnections.Add(iocf.IOConnectionInfo); UIUtil.DestroyForm(iocf); } return(Import(pwStorage, new KeePassKdb2x(), vConnections.ToArray(), true, uiOps, false, fParent)); }
public void ShouldNotExportKeeShareNodes() { m_treeManager.Initialize(m_database); var exportPath = GetTestPath(); m_syncManager.AddExportPath(exportPath); var userMrX = TestHelper.GetUserRootNodeByNameFor(m_database, "mrX"); var userMrY = TestHelper.GetUserRootNodeByNameFor(m_database, "mrY"); userMrY.SetPassword(STANDARD_PASSWORD); m_database.GetExportGroup().Groups.GetAt(0).AddEntry(userMrY.CreateProxyNode(), true); m_database.RootGroup.AddEntry(userMrX.CreateProxyNode(), true); m_treeManager.CorrectStructure(); m_database.GetUserHomeFor(userMrY).AddEntry(userMrX.CreateProxyNode(), true); m_database.GetUserHomeFor(userMrX).AddEntry(userMrY.CreateProxyNode(), true); string exportFile = exportPath + SyncSource.FileNameFor(userMrY) + SyncExporter.FileExtension; Assert.IsFalse(File.Exists(exportFile)); m_syncManager.Export(); TestHelper.DelayAction(); Assert.IsTrue(File.Exists(exportFile)); var deltaDBAdamReexport = new PwDatabase(); deltaDBAdamReexport.Open(IOConnectionInfo.FromPath(exportFile), m_standardKey, null); foreach (var entry in deltaDBAdamReexport.RootGroup.GetEntries(true)) { Assert.AreNotEqual(userMrX.GetTitle(), entry.GetTitle()); } foreach (var group in deltaDBAdamReexport.RootGroup.GetGroups(true)) { Assert.AreNotEqual(userMrX.GetTitle(), group.Name); } }
private static bool IsMatchFileExists(EcasCondition c, EcasContext ctx) { string strFile = EcasUtil.GetParamString(c.Parameters, 0, true); if (string.IsNullOrEmpty(strFile)) { return(true); } try { // return File.Exists(strFile); IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); return(IOConnection.FileExists(ioc)); } catch (Exception) { } return(false); }
/// <summary> /// Sync Google Drive File with currently open Database file /// </summary> /// <param name="downloadFilePath">Full path of database file to sync with</param> /// <returns>Return status of the update</returns> private string syncFile(string downloadFilePath) { IOConnectionInfo connection = IOConnectionInfo.FromPath(downloadFilePath); bool? success = ImportUtil.Synchronize(m_host.Database, m_host.MainWindow, connection, true, m_host.MainWindow); System.IO.File.Delete(downloadFilePath); if (!success.HasValue) { throw new PlgxException("Synchronization failed.\n\nYou do not have permission to import. Adjust your KeePass configuration."); } if (!(bool)success) { throw new PlgxException("Synchronization failed.\n\n" + "If the error was that master keys (passwords) do not match, use Upload / Download commands instead of Sync " + "or change the local master key to match that of the remote database."); } return("Local file synchronized."); }
/// <summary> /// Sync Google Drive File with currently open Database file /// </summary> /// <param name="downloadFilePath">Full path of database file to sync with</param> /// <returns>Return status of the update</returns> private string syncFile(string downloadFilePath) { IOConnectionInfo connection = IOConnectionInfo.FromPath(downloadFilePath); bool? success = ImportUtil.Synchronize(m_host.Database, m_host.MainWindow, connection, true, m_host.MainWindow); System.IO.File.Delete(downloadFilePath); if (!success.HasValue) { throw new PlgxException("同步失败。\n\n没有导入权限,请调整 KeePass 配置"); } if (!(bool)success) { throw new PlgxException("同步失败。\n\n" + "如果主密匙(密码)不正确,请使用 上传/下载 命令,而不是同步。\n\n" + "或更改本地主密匙与远程数据库的密钥一致。"); } return("本地文件同步。"); }
private bool ValidateKeyFile() { string strKeyFile = m_cmbKeyFile.Text; Debug.Assert(strKeyFile != null); if (strKeyFile == null) { strKeyFile = string.Empty; } if (strKeyFile.Equals(KPRes.NoKeyFileSpecifiedMeta)) { return(true); } if (Program.KeyProviderPool.IsKeyProvider(strKeyFile)) { return(true); } bool bSuccess = true; IOConnectionInfo ioc = IOConnectionInfo.FromPath(strKeyFile); if (!IOConnection.FileExists(ioc)) { MessageService.ShowWarning(strKeyFile, KPRes.FileNotFoundError); bSuccess = false; } // if(!bSuccess) // { // int nPos = m_cmbKeyFile.Items.IndexOf(strKeyFile); // if(nPos >= 0) // { // m_cmbKeyFile.Items.RemoveAt(nPos); // m_lKeyFileNames.RemoveAt(nPos); // } // m_cmbKeyFile.SelectedIndex = 0; // } return(bSuccess); }
private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData) { Debug.Assert(strFile != null); if (strFile == null) { throw new ArgumentNullException("strFile"); } Debug.Assert(pbKeyData != null); if (pbKeyData == null) { throw new ArgumentNullException("pbKeyData"); } IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); using (Stream s = IOConnection.OpenWrite(ioc)) { using (XmlWriter xw = XmlUtilEx.CreateXmlWriter(s)) { xw.WriteStartDocument(); xw.WriteStartElement(RootElementName); // <KeyFile> xw.WriteStartElement(MetaElementName); // <Meta> xw.WriteStartElement(VersionElementName); // <Version> xw.WriteString("1.00"); xw.WriteEndElement(); // </Version> xw.WriteEndElement(); // </Meta> xw.WriteStartElement(KeyElementName); // <Key> xw.WriteStartElement(KeyDataElementName); // <Data> xw.WriteString(Convert.ToBase64String(pbKeyData)); xw.WriteEndElement(); // </Data> xw.WriteEndElement(); // </Key> xw.WriteEndElement(); // </KeyFile> xw.WriteEndDocument(); } } }