private ICryptoTransform GetDecryptor()
        {
            var rijndael = new RijndaelManaged {
                Key = KeyProvider.GetKey(), IV = KeyProvider.GetIV()
            };

            return(rijndael.CreateDecryptor());
        }
        /// <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 ICryptoTransform GetEncryptor(string password)
        {
            if (!KeyProvider.CorrectPassword(password))
            {
                throw new Exception("Password isn`t correct");
            }
            var rijndael = new RijndaelManaged()
            {
                Key = KeyProvider.GetKey(), IV = KeyProvider.GetIV()
            };

            return(rijndael.CreateEncryptor());
        }
Example #4
0
        internal static CompositeKey CreateKey(byte[] pbPasswordUtf8,
                                               string strKeyFile, bool bUserAccount, IOConnectionInfo ioc,
                                               bool bNewKey, bool bSecureDesktop)
        {
            Debug.Assert(ioc != null);

            CompositeKey ck        = new CompositeKey();
            bool         bPassword = (pbPasswordUtf8 != null);
            string       strNP     = MessageService.NewParagraph;

            if (bPassword)
            {
                ck.AddUserKey(new KcpPassword(pbPasswordUtf8,
                                              Program.Config.Security.MasterPassword.RememberWhileOpen));
            }

            if (!string.IsNullOrEmpty(strKeyFile) && (strKeyFile !=
                                                      KPRes.NoKeyFileSpecifiedMeta))
            {
                KeyProvider kp = Program.KeyProviderPool.Get(strKeyFile);
                if (kp != null)
                {
                    byte[] pbKey = null;
                    try
                    {
                        if (bSecureDesktop && !kp.SecureDesktopCompatible)
                        {
                            throw new Exception(KPRes.KeyProvIncmpWithSD + strNP +
                                                KPRes.KeyProvIncmpWithSDHint);
                        }
                        if (kp.Exclusive && (bPassword || bUserAccount))
                        {
                            throw new Exception(KPRes.KeyProvExclusive);
                        }

                        KeyProviderQueryContext ctx = new KeyProviderQueryContext(
                            ioc, bNewKey, bSecureDesktop);

                        pbKey = kp.GetKey(ctx);

                        if ((pbKey != null) && (pbKey.Length != 0))
                        {
                            ck.AddUserKey(new KcpCustomKey(strKeyFile, pbKey,
                                                           !kp.DirectKey));
                        }
                        else
                        {
                            return(null);                         // Provider has shown error message
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(strKeyFile + strNP + ex.Message);
                    }
                    finally { if (pbKey != null)
                              {
                                  MemUtil.ZeroByteArray(pbKey);
                              }
                    }
                }
                else                 // Key file
                {
                    try { ck.AddUserKey(new KcpKeyFile(strKeyFile, bNewKey)); }
                    catch (Exception ex)
                    {
                        throw new Exception(strKeyFile + strNP + KLRes.FileLoadFailed +
                                            strNP + ex.Message);
                    }
                }
            }

            if (bUserAccount)
            {
                ck.AddUserKey(new KcpUserAccount());
            }

            return((ck.UserKeyCount != 0) ? ck : null);
        }
Example #5
0
        public FuncResult GetNodeResult <TFunctionType>() where TFunctionType : IFunc <TIn>
        {
            var key = KeyProvider.GetKey <TFunctionType>();

            return(!_results.ContainsKey(key) ? null : _results[key]);
        }
Example #6
0
        /// <summary>
        /// Exports all entries with the given tag to a new database at the given path.
        /// </summary>
        /// <param name="sourceDb">The source database.</param>
        /// <param name="settings">The settings for this job.</param>
        private static void CopyToNewDb(PwDatabase sourceDb, Settings settings)
        {
            // Create a key for the target database
            CompositeKey key = new CompositeKey();

            bool hasPassword = false;
            bool hasKeyFile  = false;

            if (!settings.Password.IsEmpty)
            {
                byte[] passwordByteArray = settings.Password.ReadUtf8();
                key.AddUserKey(new KcpPassword(passwordByteArray));
                MemUtil.ZeroByteArray(passwordByteArray);
                hasPassword = true;
            }

            // Load a keyfile for the target database if requested (and add it to the key)
            if (!string.IsNullOrEmpty(settings.KeyFilePath))
            {
                bool bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(settings.KeyFilePath);

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

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

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

                        MemUtil.ZeroByteArray(pbCustomKey);
                    }
                }
            }

            // Check if at least a password or a keyfile have been added to the key object
            if (!hasPassword && !hasKeyFile)
            {
                // Fail if not
                throw new InvalidOperationException("For the target database at least a password or a keyfile is required.");
            }

            // Create a new database
            PwDatabase targetDatabase = new PwDatabase();

            // Apply the created key to the new database
            targetDatabase.New(new IOConnectionInfo(), key);

            // Copy database settings
            targetDatabase.Color                  = sourceDb.Color;
            targetDatabase.Compression            = sourceDb.Compression;
            targetDatabase.DataCipherUuid         = sourceDb.DataCipherUuid;
            targetDatabase.DefaultUserName        = sourceDb.DefaultUserName;
            targetDatabase.Description            = sourceDb.Description;
            targetDatabase.HistoryMaxItems        = sourceDb.HistoryMaxItems;
            targetDatabase.HistoryMaxSize         = sourceDb.HistoryMaxSize;
            targetDatabase.MaintenanceHistoryDays = sourceDb.MaintenanceHistoryDays;
            targetDatabase.MasterKeyChangeForce   = sourceDb.MasterKeyChangeForce;
            targetDatabase.MasterKeyChangeRec     = sourceDb.MasterKeyChangeRec;
            targetDatabase.Name = sourceDb.Name;
            targetDatabase.RecycleBinEnabled = sourceDb.RecycleBinEnabled;

            if (settings.KeyTransformationRounds == 0)
            {
                // keyTransformationRounds was not set -> use the one from the source database
                settings.KeyTransformationRounds = sourceDb.KdfParameters.GetUInt64(AesKdf.ParamRounds, 0);
            }

            // Set keyTransformationRounds (min PwDefs.DefaultKeyEncryptionRounds)
            targetDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds, Math.Max(PwDefs.DefaultKeyEncryptionRounds, settings.KeyTransformationRounds));

            // Assign the properties of the source root group to the target root group
            targetDatabase.RootGroup.AssignProperties(sourceDb.RootGroup, false, true);
            HandleCustomIcon(targetDatabase, sourceDb, sourceDb.RootGroup);

            // Overwrite the root group name if requested
            if (!string.IsNullOrEmpty(settings.RootGroupName))
            {
                targetDatabase.RootGroup.Name = settings.RootGroupName;
            }

            // Find all entries matching the tag
            PwObjectList <PwEntry> entries = new PwObjectList <PwEntry>();

            if (!string.IsNullOrEmpty(settings.Tag) && string.IsNullOrEmpty(settings.Group))
            {
                // Tag only export
                sourceDb.RootGroup.FindEntriesByTag(settings.Tag, entries, true);
            }
            else if (string.IsNullOrEmpty(settings.Tag) && !string.IsNullOrEmpty(settings.Group))
            {
                // Tag and group export
                PwGroup groupToExport = sourceDb.RootGroup.GetFlatGroupList().FirstOrDefault(g => g.Name == settings.Group);

                if (groupToExport == null)
                {
                    throw new ArgumentException("No group with the name of the Group-Setting found.");
                }

                entries = groupToExport.GetEntries(true);
            }
            else if (!string.IsNullOrEmpty(settings.Tag) && !string.IsNullOrEmpty(settings.Group))
            {
                // Tag and group export
                PwGroup groupToExport = sourceDb.RootGroup.GetFlatGroupList().FirstOrDefault(g => g.Name == settings.Group);

                if (groupToExport == null)
                {
                    throw new ArgumentException("No group with the name of the Group-Setting found.");
                }

                groupToExport.FindEntriesByTag(settings.Tag, entries, true);
            }
            else
            {
                throw new ArgumentException("At least one of Tag or ExportFolderName must be set.");
            }


            // Copy all entries to the new database
            foreach (PwEntry entry in entries)
            {
                // Get or create the target group in the target database (including hierarchy)
                PwGroup targetGroup = CreateTargetGroupInDatebase(entry, targetDatabase, sourceDb);

                // Clone entry
                PwEntry peNew = new PwEntry(false, false);
                peNew.Uuid = entry.Uuid;
                peNew.AssignProperties(entry, false, true, true);

                // Handle custom icon
                HandleCustomIcon(targetDatabase, sourceDb, entry);

                // Add entry to the target group in the new database
                targetGroup.AddEntry(peNew, true);
            }

            // Create target folder (if not exist)
            string targetFolder = Path.GetDirectoryName(settings.TargetFilePath);

            if (targetFolder == null)
            {
                throw new ArgumentException("Can't get target folder.");
            }
            Directory.CreateDirectory(targetFolder);

            // Save the new database under the target path
            KdbxFile kdbx = new KdbxFile(targetDatabase);

            using (FileStream outputStream = new FileStream(settings.TargetFilePath, FileMode.Create))
            {
                kdbx.Save(outputStream, null, KdbxFormat.Default, new NullStatusLogger());
            }
        }