private static CompositeKey CreateCompositeKey()
        {
            var compKey = new CompositeKey();

            if (!string.IsNullOrWhiteSpace(DatabaseInfo.DatabaseKeyFileName))
            {
                compKey.AddUserKey(new KcpKeyFile(DatabaseInfo.DatabaseKeyFileFullLocation));
            }

            if (DatabaseInfo.DatabaseMasterPassword != null)
            {
                compKey.AddUserKey(new KcpPassword(GetDatabaseMasterPassword()));
            }

            if (DatabaseInfo.DatabaseMasterCustomKey != null)
            {
                if (string.IsNullOrWhiteSpace(DatabaseInfo.DatabaseMasterCustomKeyName))
                {
                    throw new ArgumentException("A Master Custom Key cannot be without a name");
                }

                compKey.AddUserKey(new KcpCustomKey(DatabaseInfo.DatabaseMasterCustomKeyName, Encoding.Default.GetBytes(DatabaseInfo.DatabaseMasterCustomKey), true));
            }

            if (DatabaseInfo.UseMasterKeyUserAccount)
            {
                compKey.AddUserKey(new KcpUserAccount());
            }

            if (compKey.UserKeyCount == 0)
            {
                throw new AccessViolationException("Your database MUST have some sort of key to access the database itself. blank key or passwords are not allowed.");
            }
            return(compKey);
        }
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.SettingPassword);
            PwDatabase   pm     = _app.GetDb().KpDatabase;
            CompositeKey newKey = new CompositeKey();

            if (String.IsNullOrEmpty(_password) == false)
            {
                newKey.AddUserKey(new KcpPassword(_password));
            }
            if (String.IsNullOrEmpty(_keyfile) == false)
            {
                try {
                    newKey.AddUserKey(new KcpKeyFile(_keyfile));
                } catch (Exception) {
                    //TODO MessageService.ShowWarning (strKeyFile, KPRes.KeyFileError, exKF);
                    return;
                }
            }

            DateTime     previousMasterKeyChanged = pm.MasterKeyChanged;
            CompositeKey previousKey = pm.MasterKey;

            pm.MasterKeyChanged = DateTime.Now;
            pm.MasterKey        = newKey;

            // Save Database
            _onFinishToRun = new AfterSave(previousKey, previousMasterKeyChanged, pm, OnFinishToRun);
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, _dontSave);

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
        private static CompositeKey KeyFromCommandLine(CommandLineArgs args,
                                                       string strPrefix)
        {
            CompositeKey cmpKey = new CompositeKey();

            string strPw      = args[strPrefix + AppDefs.CommandLineOptions.Password];
            string strPwEnc   = args[strPrefix + AppDefs.CommandLineOptions.PasswordEncrypted];
            string strFile    = args[strPrefix + AppDefs.CommandLineOptions.KeyFile];
            string strUserAcc = args[strPrefix + AppDefs.CommandLineOptions.UserAccount];

            if (strPw != null)
            {
                cmpKey.AddUserKey(new KcpPassword(strPw));
            }
            else if (strPwEnc != null)
            {
                cmpKey.AddUserKey(new KcpPassword(StrUtil.DecryptString(strPwEnc)));
            }

            if (strFile != null)
            {
                cmpKey.AddUserKey(new KcpKeyFile(strFile));
            }

            if (strUserAcc != null)
            {
                cmpKey.AddUserKey(new KcpUserAccount());
            }

            return(cmpKey);
        }
Example #4
0
        /// <summary>
        /// Convert the KeyList object to a composite key
        /// </summary>
        /// <param name="kList">KeyList containing the composite key information.</param>
        /// <returns>CompositeKey object.</returns>
        internal static CompositeKey ConvertToComposite(KeyList kList)
        {
            if (kList.Pass == null || kList.KeyName == null)
            {
                return(null);
            }
            int          kNumber = kList.Pass.Count();
            int          i       = 0;
            CompositeKey mKey    = new CompositeKey();

            for (i = 0; i < kNumber; ++i)
            {
                switch (kList.KeyName[i])
                {
                case "KeePassLib.Keys.KcpPassword":
                    byte[]   pb       = kList.Pass[i].ReadUtf8();
                    IUserKey mKeyPass = new KcpPassword(pb);
                    MemUtil.ZeroByteArray(pb);
                    mKey.AddUserKey(mKeyPass);
                    break;

                case "KeePassLib.Keys.KcpKeyFile":
                    IUserKey mKeyFile = new KcpKeyFile(kList.Pass[i].ReadString());
                    mKey.AddUserKey(mKeyFile);
                    break;

                case "KeePassLib.Keys.KcpUserAccount":
                    IUserKey mKeyUser = new KcpUserAccount();
                    mKey.AddUserKey(mKeyUser);
                    break;
                }
            }
            return(mKey);
        }
Example #5
0
        public void Decryption(string path, string password, bool hasKey, int count)
        {
            var key = new CompositeKey();

            if (password != null)
            {
                key.AddUserKey(new KcpPassword("12345"));
            }

            if (hasKey)
            {
                var keyPath = $"{Path.GetFileNameWithoutExtension(path)}.key";
                key.AddUserKey(new KcpKeyFile(File.ReadAllBytes(GetFullPath(keyPath))));
            }

            var db = new PwDatabase
            {
                MasterKey = key
            };

            var file = new KdbxFile(db);

            file.Load(GetFullPath(path), KdbxFormat.Default, null);

            Assert.Equal(count, (int)db.RootGroup.Entries.UCount);
        }
Example #6
0
        private static CompositeKey KeyFromCmdLine(CommandLineArgs args)
        {
            CompositeKey cmpKey = new CompositeKey();

            string strPw = args[AppDefs.CommandLineOptions.Password];

            if (strPw != null)
            {
                cmpKey.AddUserKey(new KcpPassword(strPw));
            }

            string strFile = args[AppDefs.CommandLineOptions.KeyFile];

            if (strFile != null)
            {
                cmpKey.AddUserKey(new KcpKeyFile(strFile));
            }

            string strUserAcc = args[AppDefs.CommandLineOptions.UserAccount];

            if (strUserAcc != null)
            {
                cmpKey.AddUserKey(new KcpUserAccount());
            }

            return(cmpKey);
        }
Example #7
0
        protected TestKp2aApp SetupAppWithDatabase(string filename)
        {
            TestKp2aApp app = CreateTestKp2aApp();

            IOConnectionInfo ioc = new IOConnectionInfo {
                Path = filename
            };
            Database db = app.CreateNewDatabase();

            if (filename.EndsWith(".kdb"))
            {
                db.DatabaseFormat = new KdbDatabaseFormat(app);
            }

            db.KpDatabase = new PwDatabase();

            CompositeKey compositeKey = new CompositeKey();

            compositeKey.AddUserKey(new KcpPassword(DefaultPassword));
            if (!String.IsNullOrEmpty(DefaultKeyfile))
            {
                compositeKey.AddUserKey(new KcpKeyFile(DefaultKeyfile));
            }
            db.KpDatabase.New(ioc, compositeKey);


            db.KpDatabase.KeyEncryptionRounds = 3;
            db.KpDatabase.Name = "Keepass2Android Testing Password Database";


            // Set Database state
            db.Root         = db.KpDatabase.RootGroup;
            db.Loaded       = true;
            db.SearchHelper = new SearchDbHelper(app);

            // Add a couple default groups
            db.KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "Internet", PwIcon.Key), true);

            mailGroup = new PwGroup(true, true, "eMail", PwIcon.UserCommunication);
            db.KpDatabase.RootGroup.AddGroup(mailGroup, true);

            mailGroup.AddGroup(new PwGroup(true, true, "business", PwIcon.BlackBerry), true);

            mailEntry = new PwEntry(true, true);
            mailEntry.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                                      true, "*****@*****.**"));
            mailEntry.Strings.Set(PwDefs.TitleField, new ProtectedString(
                                      true, "[email protected] Entry"));
            mailGroup.AddEntry(mailEntry, true);

            db.KpDatabase.RootGroup.AddGroup(new PwGroup(true, true, "eMail2", PwIcon.UserCommunication), true);

            return(app);
        }
Example #8
0
        protected static CompositeKey CreateKey(string password, string keyfile)
        {
            CompositeKey key = new CompositeKey();

            key.AddUserKey(new KcpPassword(password));
            if (!String.IsNullOrEmpty(keyfile))
            {
                key.AddUserKey(new KcpKeyFile(keyfile));
            }
            return(key);
        }
Example #9
0
        public CompositeKey GetFromRecovery(ProtectedBinary recovery)
        {
            CompositeKey NewKey = null;

            NewKey = new CompositeKey();
            NewKey.AddUserKey(new KeyData(recovery));
            NewKey.AddUserKey(new KcpPassword("TR"));

            m_DualPassword = NewKey;

            return(NewKey);
        }
        /// <summary>
        /// Adds a keyfile to a <see cref="CompositeKey"/>.
        /// </summary>
        /// <param name="keyFilePath">The path to the keyfile to add to the <see cref="CompositeKey"/>.</param>
        /// <param name="key">The <see cref="CompositeKey"/> to add the keyfile to.</param>
        /// <param name="connectionInfo">The <see cref="IOConnectionInfo"/> object of the database (required for <see cref="KeyProviderQueryContext"/>).</param>
        /// <returns>true if sucessfull, false otherwise.</returns>
        public static bool AddKeyfileToKey(string keyFilePath, CompositeKey key, IOConnectionInfo connectionInfo)
        {
            bool success = false;

            if (!File.Exists(keyFilePath))
            {
                return(false);
            }

            bool bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(keyFilePath);

            if (!bIsKeyProv)
            {
                try
                {
                    key.AddUserKey(new KcpKeyFile(keyFilePath, true));
                    success = true;
                }
                catch (InvalidDataException exId)
                {
                    MessageService.ShowWarning(keyFilePath, exId);
                }
                catch (Exception exKf)
                {
                    MessageService.ShowWarning(keyFilePath, KPRes.KeyFileError, exKf);
                }
            }
            else
            {
                KeyProviderQueryContext ctxKp = new KeyProviderQueryContext(connectionInfo, true, false);

                KeyProvider prov         = Program.KeyProviderPool.Get(keyFilePath);
                bool        bPerformHash = !prov.DirectKey;
                byte[]      pbCustomKey  = prov.GetKey(ctxKp);

                if ((pbCustomKey != null) && (pbCustomKey.Length > 0))
                {
                    try
                    {
                        key.AddUserKey(new KcpCustomKey(keyFilePath, pbCustomKey, bPerformHash));
                        success = true;
                    }
                    catch (Exception exCkp)
                    {
                        MessageService.ShowWarning(exCkp);
                    }

                    MemUtil.ZeroByteArray(pbCustomKey);
                }
            }

            return(success);
        }
        private void CreateDatabase(bool makeCurrent)
        {
            var    keyfileCheckbox = FindViewById <CheckBox>(Resource.Id.use_keyfile);
            string password;

            if (!TryGetPassword(out password))
            {
                return;
            }


            // Verify that a password or keyfile is set
            if (password.Length == 0 && !keyfileCheckbox.Checked)
            {
                Toast.MakeText(this, Resource.String.error_nopass, ToastLength.Long).Show();
                return;
            }

            //create the key
            CompositeKey newKey = new CompositeKey();

            if (String.IsNullOrEmpty(password) == false)
            {
                newKey.AddUserKey(new KcpPassword(password));
            }
            if (String.IsNullOrEmpty(_keyfileFilename) == false)
            {
                try
                {
                    var ioc = IOConnectionInfo.FromPath(_keyfileFilename);
                    using (var stream = App.Kp2a.GetFileStorage(ioc).OpenFileForRead(ioc))
                    {
                        byte[] keyfileData = Util.StreamToMemoryStream(stream).ToArray();
                        newKey.AddUserKey(new KcpKeyFile(keyfileData, ioc, true));
                    }
                }
                catch (Exception)
                {
                    Toast.MakeText(this, Resource.String.error_adding_keyfile, ToastLength.Long).Show();
                    return;
                }
            }

            // Create the new database
            CreateDb     create     = new CreateDb(App.Kp2a, this, _ioc, new LaunchGroupActivity(_ioc, this), false, newKey, makeCurrent);
            ProgressTask createTask = new ProgressTask(
                App.Kp2a,
                this, create);

            createTask.Run();
        }
        private CompositeKey CreateCompositeKey(Credentials credentials)
        {
            var compositeKey = new CompositeKey();

            if (credentials.Password != null)
            {
                compositeKey.AddUserKey(new KcpPassword(credentials.Password));
            }
            if (credentials.KeyFileContents != null)
            {
                compositeKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromByteArray(credentials.KeyFileContents)));
            }
            return(compositeKey);
        }
Example #13
0
        public CompositeKey DeriveDualKey()
        {
            CompositeKey NewKey = new CompositeKey();

            foreach (var Key in Host.Database.MasterKey.UserKeys)
            {
                NewKey.AddUserKey(Key);
            }

            NewKey.AddUserKey(new KcpPassword("TR"));

            m_DualPassword = NewKey;

            return(NewKey);
        }
Example #14
0
        public void New_Test()
        {
            IFolder folder   = SpecialFolder.Current.Local;
            IFolder testData = folder.CreateFolderAsync("TestData",
                                                        CreationCollisionOption.OpenIfExists).Result;
            IFile file = testData.CreateFileAsync("1.kdbx",
                                                  CreationCollisionOption.ReplaceExisting).Result;

            var ci = new IOConnectionInfo();

            ci.Path = file.Path;
            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword("0"));
            var db = new PwDatabase();

            db.New(ci, key);
            var initialEnitiesCount = db.RootGroup.GetEntriesCount(true);

            Assert.AreNotEqual(0, initialEnitiesCount);
            db.Save(null);
            db.Close();
            Assert.IsNull(db.RootGroup);
            db = new PwDatabase();
            db.Open(ci, key, null);
            Assert.AreEqual(initialEnitiesCount,
                            db.RootGroup.GetEntriesCount(true));
        }
Example #15
0
        private static void ExportKdbx2Xml(string kdbx2ExportPath, string kdbx2ExportPassword)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var pwbDatabase = new PwDatabase();

            var cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpPassword(kdbx2ExportPassword));

            var ioc = IOConnectionInfo.FromPath(kdbx2ExportPath);

            pwbDatabase.Open(ioc, cmpKey, null);

            var xmlExportFile = new KdbxFile(pwbDatabase);
            var xmlPath       = Path.GetDirectoryName(kdbx2ExportPath) + Path.DirectorySeparatorChar
                                + Path.GetFileNameWithoutExtension(kdbx2ExportPath) + ".xml";
            var fileStream = new FileStream(xmlPath, FileMode.Create);

            xmlExportFile.Save(fileStream, null, KdbxFormat.PlainXml, null);
            var elapsed = stopwatch.Elapsed;

            Console.WriteLine($"{elapsed.TotalSeconds}s to export [{kdbx2ExportPath}] to [{xmlPath}]");
        }
Example #16
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var ioConnectionInfo = new IOConnectionInfo()
            {
                Path = databasePath
            };

            var key = new CompositeKey();

            key.AddUserKey(new KcpPassword(databasePassword));

            var pwDatabase = new PwDatabase();

            pwDatabase.Open(ioConnectionInfo, key, null);

            var fieldMapper = new InMemoryFieldMapper()
            {
                HostAddress      = "IP Address",
                ConnectionMethod = "OS"
            };

            IPasswordChangerTreeNode treeNode = PasswordChangerTreeNode.Build(pwDatabase, fieldMapper);

            var pwChangerServiceFactory = new PasswordChangerServiceFactory(
                new PasswordDatabase(pwDatabase),
                new FakePasswordChangerExFactoryThatThrowsException()
                );

            var formBatchPasswordChanger = new FormBatchPasswordChanger(treeNode, pwChangerServiceFactory);

            Application.Run(formBatchPasswordChanger);
        }
Example #17
0
        private static void ResaveKdbx(string kdbx2ExportPath, string kdbx2ExportPassword)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var pwbDatabase = new PwDatabase();

            var cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpPassword(kdbx2ExportPassword));

            var ioc = IOConnectionInfo.FromPath(kdbx2ExportPath);

            pwbDatabase.Open(ioc, cmpKey, null);

            var elapsed = stopwatch.Elapsed;

            Console.WriteLine($"{elapsed.TotalSeconds}s to load [{kdbx2ExportPath}]");

            stopwatch.Reset();

            var duplicate = new KdbxFile(pwbDatabase);
            var dupPath   = Path.GetDirectoryName(kdbx2ExportPath)
                            + Path.DirectorySeparatorChar
                            + Path.GetFileNameWithoutExtension(kdbx2ExportPath)
                            + ".dup"
                            + Path.GetExtension(kdbx2ExportPath);
            var fileStream = new FileStream(dupPath, FileMode.Create);

            duplicate.Save(fileStream, null, KdbxFormat.Default, null);

            Console.WriteLine($"{elapsed.TotalSeconds}s to save [{kdbx2ExportPath}] to [{dupPath}]");
        }
Example #18
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (m_bIsNew)
            {
                if (txtPassword.Text == "")
                {
                    MessageBox.Show(this, "Password can not be blank", "Blank Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    DialogResult = DialogResult.None;
                    txtPassword.Focus();
                    return;
                }


                if (!txtPassword.TextEx.Equals(txtPassword2.TextEx, false))
                {
                    MessageBox.Show(this, "Passwords do not match!", "Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    DialogResult = DialogResult.None;
                    txtPassword.Focus();
                    return;
                }
            }

            Password = new CompositeKey();

            byte[] pb = txtPassword.TextEx.ReadUtf8();
            Password.AddUserKey(new KcpPassword(pb));
            Array.Clear(pb, 0, pb.Length);

            DialogResult = DialogResult.OK;
        }
Example #19
0
        public static CompositeKey CreateKeyFor(string password)
        {
            CompositeKey key = new CompositeKey();

            key.AddUserKey(new KcpPassword(password));
            return(key);
        }
        private bool CreateCompositeKey()
        {
            m_pKey = new CompositeKey();

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

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

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

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

            byte[] pb = m_secPassword.ToUtf8();

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

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

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

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

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

            return(true);
        }
Example #21
0
        private static CompositeKey CreateCompositeKey(ProtectedString password, string keyFilePath)
        {
            CompositeKey key = new CompositeKey();

            if (!password.IsEmpty)
            {
                IUserKey mKeyPass = new KcpPassword(password.ReadUtf8());
                key.AddUserKey(mKeyPass);
            }

            // Load a keyfile for the target database if requested (and add it to the key)
            if (!string.IsNullOrEmpty(keyFilePath))
            {
                IUserKey mKeyFile = new KcpKeyFile(keyFilePath);
                key.AddUserKey(mKeyFile);
            }

            return(key);
        }
        /// <summary>
        /// Adds a password to a <see cref="CompositeKey"/>.
        /// </summary>
        /// <param name="password">The password to add to the <see cref="CompositeKey"/>.</param>
        /// <param name="key">The <see cref="CompositeKey"/> to add the password to.</param>
        /// <returns>true if sucessfull, false otherwise.</returns>
        public static bool AddPasswordToKey(string password, CompositeKey key)
        {
            if (password == "")
            {
                return(false);
            }

            key.AddUserKey(new KcpPassword(password));
            return(true);
        }
        /// <summary>
        /// Adds a password to a <see cref="CompositeKey"/>.
        /// </summary>
        /// <param name="passwordByteArray">The password as byte array to add to the <see cref="CompositeKey"/>.</param>
        /// <param name="key">The <see cref="CompositeKey"/> to add the password to.</param>
        /// <returns>true if sucessfull, false otherwise.</returns>
        public static bool AddPasswordToKey(byte[] passwordByteArray, CompositeKey key)
        {
            if (passwordByteArray.Length == 0)
            {
                return(false);
            }

            key.AddUserKey(new KcpPassword(passwordByteArray));
            return(true);
        }
Example #24
0
        public KeePassFixture()
        {
            Logger = new KPCLibLogger();
            PwDb   = new PwDatabase();
            IOConnectionInfo ioc    = IOConnectionInfo.FromPath(TEST_DB);
            CompositeKey     cmpKey = new CompositeKey();

            cmpKey.AddUserKey(new KcpPassword(TEST_DB_KEY));
            PwDb.Open(ioc, cmpKey, Logger);
        }
Example #25
0
        private static bool ChangeMasterKey(PwDatabase pwDatabase, CommandLineArgs args)
        {
            const string strNew = "new";

            CompositeKey ck = new CompositeKey();

            string strPw    = args[strNew + AppDefs.CommandLineOptions.Password];
            string strPwEnc = args[strNew + AppDefs.CommandLineOptions.PasswordEncrypted];

            if (strPw != null)
            {
                ck.AddUserKey(new KcpPassword(strPw));
            }
            else if (strPwEnc != null)
            {
                ck.AddUserKey(new KcpPassword(StrUtil.DecryptString(strPwEnc)));
            }

            string strFile = args[strNew + AppDefs.CommandLineOptions.KeyFile];

            if (!string.IsNullOrEmpty(strFile))
            {
                ck.AddUserKey(new KcpKeyFile(strFile));
            }

            string strAcc = args[strNew + AppDefs.CommandLineOptions.UserAccount];

            if (strAcc != null)
            {
                ck.AddUserKey(new KcpUserAccount());
            }

            if (ck.UserKeyCount > 0)
            {
                pwDatabase.MasterKey                = ck;
                pwDatabase.MasterKeyChanged         = DateTime.UtcNow;
                pwDatabase.MasterKeyChangeForceOnce = false;
                return(true);
            }

            return(false);
        }
Example #26
0
        public ICollection <SecretEntryModel> ReadDatabase(string databasePath, string masterPassword)
        {
            _stringValidator.IsNullOrWhitespace(databasePath, nameof(databasePath));
            _stringValidator.IsNullOrWhitespace(masterPassword, nameof(masterPassword));
            _fileValidator.IsExist(databasePath);

            //How to read KeePass database taken from https://stackoverflow.com/a/9028433

            var result = default(ICollection <SecretEntryModel>);

            var connection = new IOConnectionInfo {
                Path = databasePath
            };
            var compositeKey = new CompositeKey();
            var password     = new KcpPassword(masterPassword);

            compositeKey.AddUserKey(password);
            var database = new KeePassLib.PwDatabase();

            try
            {
                database.Open(connection, compositeKey, null);

                var readData = from entry in database.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")
                };
                result = readData.Select(data => new SecretEntryModel
                {
                    Title    = data.Title,
                    UserName = data.UserName,
                    Password = data.Password,
                }).ToList();
            }
            catch (Exception exception)
            {
                Log.Logger.Error(exception, $"During reading KeePass database {databasePath} an error has been occured");
            }
            finally
            {
                if (database.IsOpen)
                {
                    database.Close();
                }
            }

            return(result);
        }
Example #27
0
        /// <summary>
        /// Method for opening and decypting Database
        /// </summary>
        /// <param name="filePath">filepath of database</param>
        /// <param name="password">password of Database</param>
        public void openDatabase(String filePath, String password)
        {
            CompositeKey cmpKey = new CompositeKey();

            byte[] pbPw = StrUtil.Utf8.GetBytes(password);
            cmpKey.AddUserKey(new KcpPassword(pbPw, Program.Config.Security.MasterPassword.RememberWhileOpen));

            IOConnectionInfo conInfo = IOConnectionInfo.FromPath(filePath);

            Program.MainForm.OpenDatabase(conInfo, cmpKey, false);
        }
Example #28
0
        private CompositeKey CreateCompositeKey(string masterKey)
        {
            CompositeKey m_pKey = new CompositeKey();

            SecureEdit se = new SecureEdit(masterKey);

            byte[] pb = se.ToUtf8();
            m_pKey.AddUserKey(new KcpPassword(pb));
            Array.Clear(pb, 0, pb.Length);

            return(m_pKey);
        }
Example #29
0
        public static CompositeKey CreatePasswordDatabaseKey(SecureString masterPassword, string keyFile, bool windowsUserAccount)
        {
            var key = new CompositeKey();

            if (masterPassword != null)
            {
                key.AddUserKey(new KcpPassword(masterPassword.ToByteArray(Encoding.UTF8)));
            }

            if (!string.IsNullOrEmpty(keyFile))
            {
                key.AddUserKey(new KcpKeyFile(keyFile));
            }

            if (windowsUserAccount)
            {
                key.AddUserKey(new KcpUserAccount());
            }

            return(key);
        }
        public override bool Initialize(IPluginHost host)
        {
            if (host == null)
            {
                return(false);
            }

            _host         = host;
            _customConfig = PluginConfig.Init(_host.CustomConfig);

            KeePass.Util.UpdateCheckEx.SetFileSigKey(UpdateUrl, "<RSAKeyValue><Modulus>0qk0X8E7nOAvNUd3qQoUUpRh2JKIn4k3x95F30ToHEXasJXphNSfCwIa7Ci8Ij0rPU2sycuJVM9k6F5D4Nx2w/h/Eg8/sPEKeRJFuIVIDnGZMV15ven08Ya1LrV3/UeUh6TZ58VulyHssHiNy9U4h+STohbVueShgvfKq7HmOS1Jbaz0atr5mewqUzyyXZTx/U2DN2vwsksQYQJCJWre5hy2nPHmCukEuPthiWj8DlU2PRbAisEWc6JYj3O/64h3X8qVaPjZbSUwz/liFwfRv+1W6TNjAgqYBGhq5JV4wx9PohD4a34xZJOYLN1TwjtMDoD+ILaKA5tjPahj7lb3VYubcegt+hmR18GEceEJwCC4pa1yyP+GYz0/aeKkfP+1h3bItcJrdrALDSYNqF9+Ux+8hm7NrGt6LkJFK5iJhcp/W/Vm7EwySaUBlf7/zI7jfgO98jLUv3lxunwffWVWlZn2YFIeZMqXahGG6CpfYkU7nmbVRDecWNk5EJkhZDZHf0S2Y8eM5Spw7SJI45nhHNNRsXkUxGVLyB4yMm3M8DpTKi8Gv2vHBfQCFWktRZ9HeGsZUNatffMgh8K1HxBUfVu2XVcB7BbB5Xp/9Ela3rRUK6ByG7RJMYjefaPxt6MLQzQVVBw7HFTaYOBKbZI2cU0CyDNBVLAuDC4ETf6EhKE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");

            do
            {
                // deux cas possibles :
                // lorsque Keepass charge le plugin pour la première fois
                // lorsque le mot de passe ne permet pas d'ouvrir le base de données
                if (!_customConfig.IsConfigured.Get())
                {
                    OpenOptions();
                }

                if (!_customConfig.IsEnabled.Get())
                {
                    return(true);
                }

                // récupération de la base de données
                IOConnectionInfo db = new IOConnectionInfo();
                db.Path = _customConfig.DatabaseLocation.Get();

                // master password
                string       password = _customConfig.Password.Get();
                CompositeKey cp       = new CompositeKey();
                cp.AddUserKey(new KcpPassword(password));

                // tentative de connexion à la base de données
                // si la connexion échoue alors on considère que le plugin est mal configuré et l'utilisateur devra donc le reconfiguré
                try
                {
                    _host.Database.Open(db, cp, null);
                    // permet d'afficher la base de données dans l'interface de Keepass
                    _host.MainWindow.UpdateUI(true, null, true, null, true, null, false);
                }
                catch (System.Exception)
                {
                    MessageBox.Show("KeePassAutoUnlock : Impossible to open the database");
                    _customConfig.IsConfigured.Set(false);
                }
            } while (!_customConfig.IsConfigured.Get());

            return(true);
        }