Пример #1
0
        private void OnClickKeyFileCreate(object sender, EventArgs e)
        {
            SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.KeyFileCreate,
                                                               UrlUtil.StripExtension(UrlUtil.GetFileName(m_ioInfo.Path)) + "." +
                                                               AppDefs.FileExtension.KeyFile, UIUtil.CreateFileTypeFilter("key",
                                                                                                                          KPRes.KeyFiles, true), 1, "key", null);

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (EntropyForm dlg = new EntropyForm())
                {
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        byte[] pbAdditionalEntropy = dlg.GeneratedEntropy;

                        try
                        {
                            KcpKeyFile.Create(sfd.FileName, pbAdditionalEntropy);
                        }
                        catch (Exception exKC)
                        {
                            MessageService.ShowWarning(exKC);
                        }
                    }
                }

                EnableUserControls();
            }
        }
Пример #2
0
        public void TestConstruct()
        {
            var expectedKeyData = new byte[32] {
                0xC1, 0xB1, 0x12, 0x77, 0x23, 0xB8, 0x99, 0xB8,
                0xB9, 0x3B, 0x1B, 0xFF, 0x6C, 0xBE, 0xA1, 0x5B,
                0x8B, 0x99, 0xAC, 0xBD, 0x99, 0x51, 0x85, 0x95,
                0x31, 0xAA, 0x14, 0x3D, 0x95, 0xBF, 0x63, 0xFF
            };

            var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);

            using (var fs = new FileStream(fullPath, FileMode.Create)) {
                using (var sw = new StreamWriter(fs)) {
                    sw.Write(expectedFileStart);
                    sw.Write(testKey);
                    sw.Write(expectedFileEnd);
                }
            }

            try {
                var keyFile = new KcpKeyFile(fullPath);
                var keyData = keyFile.KeyData.ReadData();
                Assert.That(keyData, Is.EqualTo(expectedKeyData));
            } finally {
                File.Delete(fullPath);
            }
        }
Пример #3
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);
        }
Пример #4
0
        private string CreateKeyFile()
        {
            byte[] pbEntropy = null;
            if (m_cbNewEntropy.Checked)
            {
                EntropyForm dlg = new EntropyForm();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    pbEntropy = dlg.GeneratedEntropy;
                }
                UIUtil.DestroyForm(dlg);

                if (pbEntropy == null)
                {
                    return(null);
                }
            }

            string strFilePath = GetKeyFilePath();

            if (string.IsNullOrEmpty(strFilePath))
            {
                return(null);
            }

            KcpKeyFile.Create(strFilePath, pbEntropy, m_vNewFormat[
                                  m_cmbNewFormat.SelectedIndex].Version);
            return(strFilePath);
        }
Пример #5
0
        public void TestConstruct()
        {
            var expectedKeyData = new byte[]
            {
                0x95, 0x94, 0xdc, 0xb9, 0x91, 0xc6, 0x65, 0xa0,
                0x81, 0xf6, 0x6f, 0xca, 0x07, 0x1a, 0x30, 0xd1,
                0x1d, 0x65, 0xcf, 0x8d, 0x9c, 0x60, 0xfb, 0xe6,
                0x45, 0xfc, 0xc8, 0x92, 0xbd, 0xeb, 0xaf, 0xc3
            };

            var folder = StorageFolder.GetFolderFromPathAsync(Path.GetTempPath()).GetAwaiter().GetResult();
            var file   = folder.CreateFileAsync(TestCreateFile, CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();

            using (var fs = file.OpenStreamForWriteAsync().GetAwaiter().GetResult())
            {
                using (var sw = new StreamWriter(fs))
                {
                    sw.Write(ExpectedFileStart);
                    sw.Write(TestKey);
                    sw.Write(ExpectedFileEnd);
                }
            }

            try
            {
                var keyFile = new KcpKeyFile(file);
                var keyData = keyFile.KeyData.ReadData();
                Assert.True(MemUtil.ArraysEqual(keyData, expectedKeyData));
            }
            finally
            {
                file.DeleteAsync().GetAwaiter().GetResult();
            }
        }
Пример #6
0
        public async Task TestConstruct()
        {
            var expectedKeyData = new byte[]
            {
                0x95, 0x94, 0xdc, 0xb9, 0x91, 0xc6, 0x65, 0xa0,
                0x81, 0xf6, 0x6f, 0xca, 0x07, 0x1a, 0x30, 0xd1,
                0x1d, 0x65, 0xcf, 0x8d, 0x9c, 0x60, 0xfb, 0xe6,
                0x45, 0xfc, 0xc8, 0x92, 0xbd, 0xeb, 0xaf, 0xc3
            };

            await using (var fs = await _file.OpenStreamForWriteAsync())
            {
                await using var sw = new StreamWriter(fs);
                sw.Write(ExpectedFileStart);
                sw.Write(TestKey);
                sw.Write(ExpectedFileEnd);
            }

            var fileBytes = (await FileIO.ReadBufferAsync(_file)).ToArray();

            var keyFile = new KcpKeyFile(fileBytes);
            var keyData = keyFile.KeyData.ReadData();

            Assert.That(MemUtil.ArraysEqual(keyData, expectedKeyData), Is.True);
        }
Пример #7
0
        public void TestConstruct()
        {
            var expectedKeyData = new byte[32] {
                0xf2, 0xd2, 0xef, 0x10, 0xc8, 0x63, 0xa6, 0x88,
                0xe3, 0x44, 0xc5, 0x7f, 0xce, 0xd5, 0x58, 0xE0,
                0x9C, 0xFF, 0xFC, 0x4D, 0x42, 0x65, 0x03, 0x69,
                0x16, 0x5B, 0xF1, 0xEF, 0xFD, 0x81, 0x10, 0x11
            };

            var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);

            using (var fs = new FileStream(fullPath, FileMode.Create))
            {
                using (var sw = new StreamWriter(fs))
                {
                    sw.Write(expectedFileStart);
                    sw.Write(testKey);
                    sw.Write(expectedFileEnd);
                }
            }

            try
            {
                var keyFile = new KcpKeyFile(fullPath);
                var keyData = keyFile.KeyData.ReadData();
                Assert.That(keyData, Is.EqualTo(expectedKeyData));
            }
            finally
            {
                File.Delete(fullPath);
            }
        }
Пример #8
0
        private void OnClickKeyFileCreate(object sender, EventArgs e)
        {
            SaveFileDialogEx sfd = UIUtil.CreateSaveFileDialog(KPRes.KeyFileCreate,
                                                               UrlUtil.StripExtension(UrlUtil.GetFileName(m_ioInfo.Path)) + "." +
                                                               AppDefs.FileExtension.KeyFile, UIUtil.CreateFileTypeFilter("key",
                                                                                                                          KPRes.KeyFiles, true), 1, "key", AppDefs.FileDialogContext.KeyFile);

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                EntropyForm dlg = new EntropyForm();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    byte[] pbAdditionalEntropy = dlg.GeneratedEntropy;

                    try
                    {
                        KcpKeyFile.Create(sfd.FileName, pbAdditionalEntropy);

                        string str = sfd.FileName;
                        m_cmbKeyFile.Items.Add(str);
                        m_cmbKeyFile.SelectedIndex = m_cmbKeyFile.Items.Count - 1;
                    }
                    catch (Exception exKC)
                    {
                        MessageService.ShowWarning(exKC);
                    }
                }
                UIUtil.DestroyForm(dlg);
            }

            EnableUserControls();
        }
Пример #9
0
        public async Task TestCreate()
        {
            var fileBytes = KcpKeyFile.Create(null);
            await FileIO.WriteBytesAsync(_file, fileBytes);

            var fileContents = await FileIO.ReadTextAsync(_file);

            Assert.That(fileContents.Length, Is.EqualTo(185));
            Assert.That(fileContents.StartsWith(ExpectedFileStart), Is.True);
            Assert.That(fileContents.EndsWith(ExpectedFileEnd), Is.True);
        }
Пример #10
0
        public CompositeKey GetCompositeKey(KeyCipher keyCipher)
        {
            var password     = keyCipher.UnProtect(_protectedPassword);
            var compositeKey = new CompositeKey();

            foreach (var data in _keys)
            {
                IUserKey key     = null;
                byte[]   rawData = null;
                if (data.KcpType != KcpType.kcpUserAccount)
                {
                    rawData = keyCipher.Decrypt(data.EncryptedData, password);
                }

                try
                {
                    switch (data.KcpType)
                    {
                    case KcpType.kcpCustomKey:
                        key = new KcpCustomKey(data.CustomName, rawData, false);
                        break;

                    case KcpType.kcpPassword:
                        key = new KcpPassword(rawData);
                        break;

                    case KcpType.kcpKeyFile:
                        key = new KcpKeyFile(Encoding.UTF8.GetString(rawData));
                        break;

                    case KcpType.kcpUserAccount:
                        key = new KcpUserAccount();
                        break;
                    }
                }
                finally
                {
                    if (rawData != null)
                    {
                        MemUtil.ZeroByteArray(rawData);
                    }
                }

                Debug.Assert(key != null);
                compositeKey.AddUserKey(key);
            }

            return(compositeKey);
        }
Пример #11
0
        public void TestCreate()
        {
            var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);

            File.Create(fullPath).Close();
            KcpKeyFile.Create(fullPath, null);
            try {
                var fileContents = File.ReadAllText(fullPath);
                Assert.That(fileContents.Length, Is.EqualTo(187));
                Assert.That(fileContents, Does.StartWith(expectedFileStart));
                Assert.That(fileContents, Does.EndWith(expectedFileEnd));
            } finally {
                File.Delete(fullPath);
            }
        }
Пример #12
0
        public void TestCreate()
        {
            var fullPath = Path.GetFullPath(testCreateFile);

            KcpKeyFile.Create(fullPath, null);
            try
            {
                var fileContents = File.ReadAllText(fullPath);
                Assert.True(fileContents.StartsWith(expectedFileStart.Replace("\r\n", Environment.NewLine)));
                Assert.True(fileContents.EndsWith(expectedFileEnd.Replace("\r\n", Environment.NewLine)));
            }
            finally
            {
                File.Delete(fullPath);
            }
        }
Пример #13
0
        public void TestCreate()
        {
            var folder = StorageFolder.GetFolderFromPathAsync(Path.GetTempPath()).GetAwaiter().GetResult();
            var file   = folder.CreateFileAsync(TestCreateFile, CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();

            KcpKeyFile.Create(file, null);
            try
            {
                var fileContents = FileIO.ReadTextAsync(file).GetAwaiter().GetResult();

                Assert.Equal(185, fileContents.Length);
                Assert.StartsWith(ExpectedFileStart, fileContents);
                Assert.EndsWith(ExpectedFileEnd, fileContents);
            }
            finally
            {
                file.DeleteAsync().GetAwaiter().GetResult();
            }
        }
Пример #14
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);
        }
Пример #15
0
        private static string GenerateHtml(PwDatabase pd, string strName)
        {
            bool   bRtl        = Program.Translation.Properties.RightToLeft;
            string strLogLeft  = (bRtl ? "right" : "left");
            string strLogRight = (bRtl ? "left" : "right");

            GFunc <string, string> h  = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> ne = delegate(string str)
            {
                if (string.IsNullOrEmpty(str))
                {
                    return("&nbsp;");
                }
                return(str);
            };
            GFunc <string, string> ltrPath = delegate(string str)
            {
                return(bRtl ? StrUtil.EnsureLtrPath(str) : str);
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html>");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" xml:lang=\"" + strLang + "\" lang=\"" + strLang + "\"");
            if (bRtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            sb.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.Append("<title>");
            sb.Append(h(strName + " - " + KPRes.EmergencySheet));
            sb.AppendLine("</title>");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            string strFont = "\"Arial\", \"Tahoma\", \"Verdana\", sans-serif;";

            // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
            if (Program.Translation.IsFor("fa"))
            {
                strFont = "\"Tahoma\", \"Arial\", \"Verdana\", sans-serif;";
            }

            sb.AppendLine("body {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("\tfont-family: " + strFont);
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("h3, p {");
            sb.AppendLine("\tmargin: 0.5em 0em 0.5em 0em;");
            sb.AppendLine("}");

            sb.AppendLine("ol, ul {");
            sb.AppendLine("\tmargin-bottom: 0em;");
            sb.AppendLine("}");

            sb.AppendLine("h1, h2, h3 {");
            sb.AppendLine("\tfont-family: \"Verdana\", \"Arial\", \"Tahoma\", sans-serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1, h2 {");
            sb.AppendLine("\tmargin: 0pt 0pt 0pt 0pt;");
            sb.AppendLine("\ttext-align: center;");
            sb.AppendLine("}");
            sb.AppendLine("h1 {");
            sb.AppendLine("\tpadding: 3pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tpadding: 1pt 0pt 3pt 0pt;");
            sb.AppendLine("}");
            // sb.AppendLine("h3 {");
            // sb.AppendLine("\tpadding: 3pt 3pt 3pt 3pt;");
            // sb.AppendLine("\tcolor: #000000;");
            // sb.AppendLine("\tbackground-color: #EEEEEE;");
            // sb.AppendLine("\tbackground-image: -webkit-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -moz-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -ms-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: linear-gradient(to bottom, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("}");

            sb.AppendLine("a {");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover, a:active {");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("}");

            sb.AppendLine("img {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("}");

            sb.AppendLine(".withspc > li + li {");
            sb.AppendLine("\tmargin-top: 0.5em;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tbackground-color: #EEEEEE;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            // border-collapse is incompatible with border-radius
            // sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\t-webkit-border-radius: 5px;");
            sb.AppendLine("\t-moz-border-radius: 5px;");
            sb.AppendLine("\tborder-radius: 5px;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader tr td {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\tpadding: 0px 15px 0px 15px;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("}");

            sb.AppendLine("table.fillinline {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\ttable-layout: fixed;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td {");
            sb.AppendLine("\tpadding: 4pt 4pt 4pt 4pt;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td img {");
            sb.AppendLine("\tdisplay: block;");             // Inline results in additional space at the bottom
            sb.AppendLine("\tmargin: 0px " + (bRtl ? "auto 0px 0px;" : "0px 0px auto;"));
            sb.AppendLine("}");
            // sb.AppendLine("span.fillinlinesym {");
            // sb.AppendLine("\tdisplay: inline-block;");
            // sb.AppendLine("\ttransform: scale(1.75, 1.75) translate(-0.5pt, -0.5pt);");
            // sb.AppendLine("}");

            // sb.AppendLine("@media print {");
            // sb.AppendLine(".scronly {");
            // sb.AppendLine("\tdisplay: none;");
            // sb.AppendLine("}");
            // sb.AppendLine("}");

            // Add the temporary content identifier
            // (always, as the sheet should be printed, not saved)
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            ImageArchive ia = new ImageArchive();

            ia.Load(Properties.Resources.Images_App_HighRes);

            sb.AppendLine("<table class=\"docheader\"><tr>");
            sb.AppendLine("<td style=\"text-align: " + strLogLeft + ";\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KeePass")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(PwDefs.ShortProductName) + "\" /></td>");
            sb.AppendLine("<td style=\"text-align: center;\">");
            sb.AppendLine("<h1>" + h(PwDefs.ShortProductName) + "</h1>");
            sb.AppendLine("<h2>" + h(KPRes.EmergencySheet) + "</h2>");
            sb.AppendLine("</td>");
            sb.AppendLine("<td style=\"text-align: " + strLogRight + ";\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KOrganizer")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(KPRes.EmergencySheet) + "\" /></td>");
            sb.AppendLine("</tr></table>");

            sb.AppendLine("<p style=\"text-align: " + strLogRight + ";\">" +
                          h(TimeUtil.ToDisplayStringDateOnly(DateTime.Now)) + "</p>");

            const string strFillInit    = "<table class=\"fillinline\"><tr><td>";
            const string strFillInitLtr = "<table class=\"fillinline\"><tr><td dir=\"ltr\">";
            const string strFillEnd     = "</td></tr></table>";
            string       strFillSym     = "<img src=\"" + GfxUtil.ImageToDataUri(
                Properties.Resources.B48x35_WritingHand) +
                                          "\" style=\"width: 1.3714em; height: 1em;" +
                                          (bRtl ? " transform: scaleX(-1);" : string.Empty) +
                                          "\" alt=\"&#x270D;\" />";
            string strFill = strFillInit + ne(string.Empty) +
                             // "</td><td style=\"text-align: right;\"><span class=\"fillinlinesym\">&#x270D;</span>" +
                             // "</td><td style=\"text-align: " + strLogRight + ";\">" +
                             "</td><td>" +
                             strFillSym + strFillEnd;

            string strFillInitEx = (bRtl ? strFillInitLtr : strFillInit);

            IOConnectionInfo ioc = pd.IOConnectionInfo;

            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(ioc.Path))) + strFillEnd);

            // if(pd.Name.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Name) + ":</strong> " +
            //		h(pd.Name) + "</p>");
            // if(pd.Description.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Description) + ":</strong> " +
            //		h(pd.Description));

            sb.AppendLine("<p>" + h(KPRes.BackupDatabase) + " " +
                          h(KPRes.BackupLocation) + "</p>");
            sb.AppendLine(strFill);

            CompositeKey ck = pd.MasterKey;

            if (ck.UserKeyCount > 0)
            {
                sb.AppendLine("<br />");
                sb.AppendLine("<h3>" + h(KPRes.MasterKey) + "</h3>");
                sb.AppendLine("<p>" + h(KPRes.MasterKeyComponents) + "</p>");
                sb.AppendLine("<ul>");

                foreach (IUserKey k in ck.UserKeys)
                {
                    KcpPassword    p  = (k as KcpPassword);
                    KcpKeyFile     kf = (k as KcpKeyFile);
                    KcpUserAccount a  = (k as KcpUserAccount);
                    KcpCustomKey   c  = (k as KcpCustomKey);

                    if (p != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.MasterPassword) +
                                      ":</strong></p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (kf != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyFile) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(kf.Path))) + strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.BackupFile) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill);

                        sb.AppendLine("</li>");
                    }
                    else if (a != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.WindowsUserAccount) +
                                      ":</strong></p>");
                        sb.Append(strFillInitEx);
                        try
                        {
                            sb.Append(ne(h(ltrPath(Environment.UserDomainName +
                                                   "\\" + Environment.UserName))));
                        }
                        catch (Exception) { Debug.Assert(false); sb.Append(ne(string.Empty)); }
                        sb.AppendLine(strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.WindowsUserAccountBackup) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (c != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyProvider) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(c.Name))) + strFillEnd);

                        sb.AppendLine("</li>");
                    }
                    else
                    {
                        Debug.Assert(false);
                        sb.AppendLine("<li><p><strong>" + h(KPRes.Unknown) + ".</strong></p></li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");

            sb.AppendLine("<li>" + h(KPRes.EmergencySheetInfo) + "</li>");
            // sb.AppendLine("<form class=\"scronly\" action=\"#\" onsubmit=\"javascript:window.print();\">");
            // sb.AppendLine("<input type=\"submit\" value=\"&#x1F5B6; " +
            //	h(KPRes.Print) + "\" />");
            // sb.AppendLine("</form></li>");

            sb.AppendLine("<li>" + h(KPRes.DataLoss) + "</li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");

            sb.AppendLine("</body></html>");

            string strDoc = sb.ToString();

#if DEBUG
            XmlUtilEx.ValidateXml(strDoc, true);
#endif
            return(strDoc);
        }
Пример #16
0
        private static string GenerateHtml(PwDatabase pd, string strName)
        {
            StrToStrDelegate h  = new StrToStrDelegate(StrUtil.StringToHtml);
            StrToStrDelegate ne = delegate(string str)
            {
                if (string.IsNullOrEmpty(str))
                {
                    return("&nbsp;");
                }
                return(str);
            };

            StringBuilder sb   = new StringBuilder();
            bool          bRtl = Program.Translation.Properties.RightToLeft;

            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
            sb.AppendLine("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" lang=\"" + strLang + "\" xml:lang=\"" + strLang + "\"");
            if (bRtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
            sb.Append("<title>");
            sb.Append(h(strName + " - " + KPRes.EmergencySheet));
            sb.AppendLine("</title>");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.AppendLine("<style type=\"text/css\"><!--");

            sb.AppendLine("body, p, div, h1, h2, h3, h4, h5, h6, ol, ul, li, td, th, dd, dt, a {");
            sb.AppendLine("\tfont-family: \"Arial\", \"Tahoma\", \"Verdana\", sans-serif;");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("body, p, div, table {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("}");

            sb.AppendLine("p, h3 {");
            sb.AppendLine("\tmargin: 0.5em 0em 0.5em 0em;");
            sb.AppendLine("}");

            sb.AppendLine("ol, ul {");
            sb.AppendLine("\tmargin-bottom: 0em;");
            sb.AppendLine("}");

            sb.AppendLine("h1, h2, h3 {");
            sb.AppendLine("\tfont-family: \"Verdana\", \"Arial\", \"Tahoma\", sans-serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1, h2 {");
            sb.AppendLine("\ttext-align: center;");
            sb.AppendLine("\tmargin: 0pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h1 {");
            sb.AppendLine("\tfont-size: 2em;");
            sb.AppendLine("\tpadding: 3pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tfont-size: 1.5em;");
            sb.AppendLine("\tpadding: 1pt 0pt 3pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h3 {");
            sb.AppendLine("\tfont-size: 1.2em;");
            // sb.AppendLine("\tpadding: 3pt 3pt 3pt 3pt;");
            // sb.AppendLine("\tcolor: #000000;");
            // sb.AppendLine("\tbackground-color: #EEEEEE;");
            // sb.AppendLine("\tbackground-image: -webkit-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -moz-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -ms-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: linear-gradient(to bottom, #E2E2E2, #FAFAFA);");
            sb.AppendLine("}");
            sb.AppendLine("h4 { font-size: 1em; }");
            sb.AppendLine("h5 { font-size: 0.89em; }");
            sb.AppendLine("h6 { font-size: 0.6em; }");

            sb.AppendLine("a:visited {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:active {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");
            sb.AppendLine("a:link {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover {");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");

            sb.AppendLine("img {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("}");

            sb.AppendLine(".withspc > li + li {");
            sb.AppendLine("\tmargin-top: 0.5em;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tbackground-color: #EEEEEE;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            // border-collapse is incompatible with border-radius
            // sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\t-webkit-border-radius: 5px;");
            sb.AppendLine("\t-moz-border-radius: 5px;");
            sb.AppendLine("\tborder-radius: 5px;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader tr td {");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tpadding: 0px 15px 0px 15px;");
            sb.AppendLine("}");

            sb.AppendLine("table.fillinline {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td {");
            sb.AppendLine("\tpadding: 4pt 4pt 4pt 4pt;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");
            // sb.AppendLine("span.fillinlinesym {");
            // sb.AppendLine("\tdisplay: inline-block;");
            // sb.AppendLine("\ttransform: scale(1.75, 1.75) translate(-0.5pt, -0.5pt);");
            // sb.AppendLine("}");

            // sb.AppendLine("@media print {");
            // sb.AppendLine(".scronly {");
            // sb.AppendLine("\tdisplay: none;");
            // sb.AppendLine("}");
            // sb.AppendLine("}");

            // Add the temporary content identifier
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("--></style>");
            sb.AppendLine("</head><body>");

            ImageArchive ia = new ImageArchive();

            ia.Load(Properties.Resources.Images_App_HighRes);

            sb.AppendLine("<table class=\"docheader\" cellspacing=\"0\" cellpadding=\"0\"><tr>");
            sb.AppendLine("<td style=\"text-align: left;\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KeePass")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(PwDefs.ShortProductName) + "\" /></td>");
            sb.AppendLine("<td style=\"text-align: center;\">");
            sb.AppendLine("<h1>" + h(PwDefs.ShortProductName) + "</h1>");
            sb.AppendLine("<h2>" + h(KPRes.EmergencySheet) + "</h2>");
            sb.AppendLine("</td>");
            sb.AppendLine("<td style=\"text-align: right;\">");
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KOrganizer")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(KPRes.EmergencySheet) + "\" /></td>");
            sb.AppendLine("</tr></table>");

            sb.AppendLine("<p style=\"text-align: right;\">" + h(
                              TimeUtil.ToDisplayStringDateOnly(DateTime.Now)) + "</p>");

            const string strFillInit = "<table class=\"fillinline\"><tr><td>";
            const string strFillEnd  = "</td></tr></table>";
            string       strFillSym  = "<img src=\"" + GfxUtil.ImageToDataUri(
                Properties.Resources.B48x35_WritingHand) +
                                       "\" style=\"width: 1.3714em; height: 1em;\" alt=\"&#x270D;\" />";
            string strFill = strFillInit + ne(string.Empty) +
                             // "</td><td style=\"text-align: right;\"><span class=\"fillinlinesym\">&#x270D;</span>" +
                             "</td><td style=\"text-align: right;\">" + strFillSym + strFillEnd;

            IOConnectionInfo ioc = pd.IOConnectionInfo;

            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInit + ne(h(ioc.Path)) + strFillEnd);

            // if(pd.Name.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Name) + ":</strong> " +
            //		h(pd.Name) + "</p>");
            // if(pd.Description.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Description) + ":</strong> " +
            //		h(pd.Description));

            sb.AppendLine("<p>" + h(KPRes.BackupDatabase) + " " +
                          h(KPRes.BackupLocation) + "</p>");
            sb.AppendLine(strFill);

            CompositeKey ck = pd.MasterKey;

            if (ck.UserKeyCount > 0)
            {
                sb.AppendLine("<br />");
                sb.AppendLine("<h3>" + h(KPRes.MasterKey) + "</h3>");
                sb.AppendLine("<p>" + h(KPRes.MasterKeyComponents) + "</p>");
                sb.AppendLine("<ul>");

                foreach (IUserKey k in ck.UserKeys)
                {
                    KcpPassword    p  = (k as KcpPassword);
                    KcpKeyFile     kf = (k as KcpKeyFile);
                    KcpUserAccount a  = (k as KcpUserAccount);
                    KcpCustomKey   c  = (k as KcpCustomKey);

                    if (p != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.MasterPassword) +
                                      ":</strong></p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (kf != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyFile) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInit + ne(h(kf.Path)) + strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.BackupFile) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill);

                        sb.AppendLine("</li>");
                    }
                    else if (a != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.WindowsUserAccount) +
                                      ":</strong></p>");
                        sb.Append(strFillInit);
                        try
                        {
                            sb.Append(ne(h(Environment.UserDomainName + "\\" +
                                           Environment.UserName)));
                        }
                        catch (Exception) { Debug.Assert(false); sb.Append(ne(string.Empty)); }
                        sb.AppendLine(strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.WindowsUserAccountBackup) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (c != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyProvider) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInit + ne(h(c.Name)) + strFillEnd);

                        sb.AppendLine("</li>");
                    }
                    else
                    {
                        Debug.Assert(false);
                        sb.AppendLine("<li><p><strong>" + h(KPRes.Unknown) + ".</strong></p></li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");

            sb.AppendLine("<li>" + h(KPRes.EmergencySheetInfo) + "</li>");
            // sb.AppendLine("<form class=\"scronly\" action=\"#\" onsubmit=\"javascript:window.print();\">");
            // sb.AppendLine("<input type=\"submit\" value=\"&#x1F5B6; " +
            //	h(KPRes.Print) + "\" />");
            // sb.AppendLine("</form></li>");

            sb.AppendLine("<li>" + h(KPRes.DataLoss) + "</li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");

            sb.AppendLine("</body></html>");
            return(sb.ToString());
        }
 public byte[] GenerateKeyFile(byte[] additionalEntropy)
 {
     return(KcpKeyFile.Create(additionalEntropy));
 }
Пример #18
0
        private static void GenerateEms(StringBuilder sb, PwDatabase pd, string strDbFile,
                                        GFunc <string, string> h, GFunc <string, string> ne, GFunc <string, string> ltrPath,
                                        string strFillInit, string strFillInitEx, string strFillEnd, string strFill)
        {
            sb.AppendLine("<p><strong>" + h(KPRes.DatabaseFile) + ":</strong></p>");
            sb.AppendLine(strFillInitEx + ne(h(ltrPath(strDbFile))) + strFillEnd);

            // if(pd.Name.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Name) + ":</strong> " +
            //		h(pd.Name) + "</p>");
            // if(pd.Description.Length > 0)
            //	sb.AppendLine("<p><strong>" + h(KPRes.Description) + ":</strong> " +
            //		h(pd.Description));

            sb.AppendLine("<p>" + h(KPRes.BackupDatabase) + " " +
                          h(KPRes.BackupLocation) + "</p>");
            sb.AppendLine(strFill);

            CompositeKey ck = pd.MasterKey;

            if (ck.UserKeyCount > 0)
            {
                sb.AppendLine("<br />");
                sb.AppendLine("<h3>" + h(KPRes.MasterKey) + "</h3>");
                sb.AppendLine("<p>" + h(KPRes.MasterKeyComponents) + "</p>");
                sb.AppendLine("<ul>");

                foreach (IUserKey k in ck.UserKeys)
                {
                    KcpPassword    p  = (k as KcpPassword);
                    KcpKeyFile     kf = (k as KcpKeyFile);
                    KcpUserAccount a  = (k as KcpUserAccount);
                    KcpCustomKey   c  = (k as KcpCustomKey);

                    if (p != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.MasterPassword) +
                                      ":</strong></p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (kf != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyFile) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(kf.Path))) + strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.BackupFile) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill);

                        sb.AppendLine("</li>");
                    }
                    else if (a != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.WindowsUserAccount) +
                                      ":</strong></p>");
                        sb.Append(strFillInitEx);
                        try
                        {
                            sb.Append(ne(h(ltrPath(Environment.UserDomainName +
                                                   "\\" + Environment.UserName))));
                        }
                        catch (Exception) { Debug.Assert(false); sb.Append(ne(string.Empty)); }
                        sb.AppendLine(strFillEnd);

                        sb.AppendLine("<p>" + h(KPRes.WindowsUserAccountBackup) + " " +
                                      h(KPRes.BackupLocation) + "</p>");
                        sb.AppendLine(strFill + "</li>");
                    }
                    else if (c != null)
                    {
                        sb.AppendLine("<li><p><strong>" + h(KPRes.KeyProvider) +
                                      ":</strong></p>");
                        sb.AppendLine(strFillInitEx + ne(h(ltrPath(c.Name))) + strFillEnd);

                        sb.AppendLine("</li>");
                    }
                    else
                    {
                        Debug.Assert(false);
                        sb.AppendLine("<li><p><strong>" + h(KPRes.Unknown) + ".</strong></p></li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            sb.AppendLine("<br />");
            sb.AppendLine("<h3>" + h(KPRes.InstrAndGenInfo) + "</h3>");

            sb.AppendLine("<ul class=\"withspc\">");

            sb.AppendLine("<li>" + h(KPRes.EmergencySheetInfo) + "</li>");
            // sb.AppendLine("<form class=\"scronly\" action=\"#\" onsubmit=\"javascript:window.print();\">");
            // sb.AppendLine("<input type=\"submit\" value=\"&#x1F5B6; " +
            //	h(KPRes.Print) + "\" />");
            // sb.AppendLine("</form></li>");

            sb.AppendLine("<li>" + h(KPRes.DataLoss) + "</li>");
            sb.AppendLine("<li>" + h(KPRes.LatestVersionWeb) + ": <a href=\"" +
                          h(PwDefs.HomepageUrl) + "\" target=\"_blank\">" +
                          h(PwDefs.HomepageUrl) + "</a>.</li>");
            sb.AppendLine("</ul>");
        }
Пример #19
0
        private static string GenerateDoc(PwDatabase pd, bool bEmSheet, bool bKeyFile)
        {
            string strDbFile = pd.IOConnectionInfo.Path;

            KcpKeyFile kf         = (pd.MasterKey.GetUserKey(typeof(KcpKeyFile)) as KcpKeyFile);
            string     strKeyFile = ((kf != null) ? kf.Path : string.Empty);

            if (bKeyFile)
            {
                if (strKeyFile.Length == 0)
                {
                    Debug.Assert(false); return(string.Empty);
                }

                if (!KfxFile.CanLoad(strKeyFile))
                {
                    throw new FormatException(strKeyFile + MessageService.NewParagraph +
                                              KPRes.KeyFileNoXml + MessageService.NewParagraph +
                                              KPRes.KeyFilePrintReqXml + MessageService.NewParagraph +
                                              KPRes.KeyFileGenHint);
                }
            }

            string strName = UrlUtil.StripExtension(UrlUtil.GetFileName(bEmSheet ?
                                                                        strDbFile : strKeyFile));

            if (strName.Length == 0)
            {
                strName = (bEmSheet ? KPRes.Database : KPRes.KeyFile);
            }

            string strDocKind = (bEmSheet ? KPRes.EmergencySheet : KPRes.KeyFileBackup);

            bool   bRtl        = Program.Translation.Properties.RightToLeft;
            string strLogLeft  = (bRtl ? "right" : "left");
            string strLogRight = (bRtl ? "left" : "right");

            GFunc <string, string> h  = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> ne = delegate(string str)
            {
                if (string.IsNullOrEmpty(str))
                {
                    return("&nbsp;");
                }
                return(str);
            };
            GFunc <string, string> ltrPath = delegate(string str)
            {
                return(bRtl ? StrUtil.EnsureLtrPath(str) : str);
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html>");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" xml:lang=\"" + strLang + "\" lang=\"" + strLang + "\"");
            if (bRtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            sb.AppendLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.Append("<title>");
            sb.Append(h(strName + " - " + strDocKind));
            sb.AppendLine("</title>");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            string strFont = "\"Arial\", \"Tahoma\", \"Verdana\", sans-serif;";

            // https://sourceforge.net/p/keepass/discussion/329220/thread/f98dece5/
            if (Program.Translation.IsFor("fa"))
            {
                strFont = "\"Tahoma\", \"Arial\", \"Verdana\", sans-serif;";
            }

            sb.AppendLine("body {");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #FFFFFF;");
            sb.AppendLine("\tfont-family: " + strFont);
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("h3, p {");
            sb.AppendLine("\tmargin: 0.5em 0em 0.5em 0em;");
            sb.AppendLine("}");

            sb.AppendLine("ol, ul {");
            sb.AppendLine("\tmargin-bottom: 0em;");
            sb.AppendLine("}");

            sb.AppendLine("h1, h2, h3 {");
            sb.AppendLine("\tfont-family: \"Verdana\", \"Arial\", \"Tahoma\", sans-serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1, h2 {");
            sb.AppendLine("\tmargin: 0pt 0pt 0pt 0pt;");
            sb.AppendLine("\ttext-align: center;");
            sb.AppendLine("}");
            sb.AppendLine("h1 {");
            sb.AppendLine("\tpadding: 3pt 0pt 0pt 0pt;");
            sb.AppendLine("}");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tpadding: 1pt 0pt 3pt 0pt;");
            sb.AppendLine("}");
            // sb.AppendLine("h3 {");
            // sb.AppendLine("\tpadding: 3pt 3pt 3pt 3pt;");
            // sb.AppendLine("\tcolor: #000000;");
            // sb.AppendLine("\tbackground-color: #EEEEEE;");
            // sb.AppendLine("\tbackground-image: -webkit-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -moz-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: -ms-linear-gradient(top, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("\tbackground-image: linear-gradient(to bottom, #E2E2E2, #FAFAFA);");
            // sb.AppendLine("}");

            sb.AppendLine("a {");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover, a:active {");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("}");

            sb.AppendLine("img {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("}");

            sb.AppendLine(".withspc > li + li {");
            sb.AppendLine("\tmargin-top: 0.5em;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tbackground-color: #EEEEEE;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            // border-collapse is incompatible with border-radius
            // sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\t-webkit-border-radius: 5px;");
            sb.AppendLine("\t-moz-border-radius: 5px;");
            sb.AppendLine("\tborder-radius: 5px;");
            sb.AppendLine("}");

            sb.AppendLine("table.docheader tr td {");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\tpadding: 0px 15px 0px 15px;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("}");

            sb.AppendLine("table.fillinline {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: thin solid #808080;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\ttable-layout: fixed;");
            sb.AppendLine("\tempty-cells: show;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td {");
            sb.AppendLine("\tpadding: 4pt 4pt 4pt 4pt;");
            sb.AppendLine("\tvertical-align: middle;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");
            sb.AppendLine("table.fillinline tr td img {");
            sb.AppendLine("\tdisplay: block;");             // Inline results in additional space at the bottom
            sb.AppendLine("\tmargin: 0px " + (bRtl ? "auto 0px 0px;" : "0px 0px auto;"));
            sb.AppendLine("}");
            // sb.AppendLine("span.fillinlinesym {");
            // sb.AppendLine("\tdisplay: inline-block;");
            // sb.AppendLine("\ttransform: scale(1.75, 1.75) translate(-0.5pt, -0.5pt);");
            // sb.AppendLine("}");

            sb.AppendLine("table.fillinline tr td pre {");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\tborder-collapse: collapse;");
            sb.AppendLine("\twhite-space: pre-wrap;");
            sb.AppendLine("\toverflow: auto;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("}");

            // sb.AppendLine("@media print {");
            // sb.AppendLine(".scronly {");
            // sb.AppendLine("\tdisplay: none;");
            // sb.AppendLine("}");
            // sb.AppendLine("}");

            sb.AppendLine("@media print {");
            sb.AppendLine(".ems_break_before {");
            sb.AppendLine("\tpage-break-before: always;");      // CSS 2
            sb.AppendLine("\tbreak-before: page;");             // CSS 3
            sb.AppendLine("}");
            sb.AppendLine("}");

            // Add the temporary content identifier
            // (always, as the sheet should be printed, not saved)
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 12pt;");
            sb.AppendLine("}");

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            ImageArchive ia = new ImageArchive();

            ia.Load(Properties.Resources.Images_App_HighRes);

            sb.AppendLine("<table class=\"docheader\"><tr>");
            sb.AppendLine("<td style=\"text-align: " + strLogLeft + ";\">");
            Debug.Assert(Properties.Resources.B16x16_KeePass != null);             // Name ref.
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KeePass")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(PwDefs.ShortProductName) + "\" /></td>");
            sb.AppendLine("<td style=\"text-align: center;\">");
            sb.AppendLine("<h1>" + h(PwDefs.ShortProductName) + "</h1>");
            sb.AppendLine("<h2>" + h(strDocKind) + "</h2>");
            sb.AppendLine("</td>");
            sb.AppendLine("<td style=\"text-align: " + strLogRight + ";\">");
            Debug.Assert(Properties.Resources.B16x16_KOrganizer != null);             // Name ref.
            sb.AppendLine("<img src=\"" + GfxUtil.ImageToDataUri(ia.GetForObject(
                                                                     "KOrganizer")) + "\" width=\"48\" height=\"48\" alt=\"" +
                          h(strDocKind) + "\" /></td>");
            sb.AppendLine("</tr></table>");

            sb.AppendLine("<p style=\"text-align: " + strLogRight + ";\">" +
                          h(TimeUtil.ToDisplayStringDateOnly(DateTime.Now)) + "</p>");

            const string strFillInit    = "<table class=\"fillinline\"><tr><td>";
            const string strFillInitLtr = "<table class=\"fillinline\"><tr><td dir=\"ltr\">";
            const string strFillEnd     = "</td></tr></table>";
            string       strFillSym     = "<img src=\"" + GfxUtil.ImageToDataUri(
                Properties.Resources.B48x35_WritingHand) +
                                          "\" style=\"width: 1.3714em; height: 1em;" +
                                          (bRtl ? " transform: scaleX(-1);" : string.Empty) +
                                          "\" alt=\"&#x270D;\" />";
            string strFill = strFillInit + ne(string.Empty) +
                             // "</td><td style=\"text-align: right;\"><span class=\"fillinlinesym\">&#x270D;</span>" +
                             // "</td><td style=\"text-align: " + strLogRight + ";\">" +
                             "</td><td>" +
                             strFillSym + strFillEnd;

            string strFillInitEx = (bRtl ? strFillInitLtr : strFillInit);

            if (bEmSheet)
            {
                GenerateEms(sb, pd, strDbFile,
                            h, ne, ltrPath, strFillInit, strFillInitEx, strFillEnd, strFill);
            }
            if (bEmSheet && bKeyFile)
            {
                sb.AppendLine("<table class=\"docheader ems_break_before\"><tr>");
                sb.AppendLine("<td style=\"text-align: center;\">");
                sb.AppendLine("<h2>" + h(KPRes.KeyFileBackup) + "</h2>");
                sb.AppendLine("</td></tr></table><br />");
            }
            if (bKeyFile)
            {
                GenerateKfb(sb, pd, strDbFile, strKeyFile,
                            h, ne, ltrPath, strFillInit, strFillInitEx, strFillEnd, strFill);
            }

            sb.AppendLine("</body></html>");

            string strDoc = sb.ToString();

#if DEBUG
            XmlUtilEx.ValidateXml(strDoc, true);
#endif
            return(strDoc);
        }
Пример #20
0
        public void PopulateDatabaseFromStream(PwDatabase db, Stream s, IStatusLogger slLogger)
        {
                        #if !EXCLUDE_KEYTRANSFORM
            var importer = new Com.Keepassdroid.Database.Load.ImporterV3();

            var hashingStream = new HashingStreamEx(s, false, new SHA256Managed());

            _metaStreams = new List <PwEntryV3>();

            string      password    = "";    //no need to distinguish between null and "" because empty passwords are invalid (and null is not allowed)
            KcpPassword passwordKey = (KcpPassword)db.MasterKey.GetUserKey(typeof(KcpPassword));
            if (passwordKey != null)
            {
                password = passwordKey.Password.ReadString();
            }

            KcpKeyFile   passwordKeyfile = (KcpKeyFile)db.MasterKey.GetUserKey(typeof(KcpKeyFile));
            MemoryStream keyfileStream   = null;
            if (passwordKeyfile != null)
            {
                keyfileStream = new MemoryStream(passwordKeyfile.RawFileData.ReadData());
            }


            try
            {
                var dbv3 = importer.OpenDatabase(hashingStream, password, keyfileStream);

                db.Name          = dbv3.Name;
                db.KdfParameters = (new AesKdf()).GetDefaultParameters();
                db.KdfParameters.SetUInt64(AesKdf.ParamRounds, (ulong)dbv3.NumKeyEncRounds);


                db.RootGroup = ConvertGroup(dbv3.RootGroup);
                if (dbv3.Algorithm == PwEncryptionAlgorithm.Rjindal)
                {
                    db.DataCipherUuid = StandardAesEngine.AesUuid;
                }
                else
                {
                    db.DataCipherUuid = new PwUuid(TwofishCipher.TwofishCipherEngine.TwofishCipherUuidBytes);
                }
            }
            catch (Java.IO.FileNotFoundException e)
            {
                throw new FileNotFoundException(
                          e.Message, e);
            }
            catch (Java.Lang.Exception e)
            {
                if (e.Message == "Invalid key!")
                {
                    throw new InvalidCompositeKeyException();
                }
                throw new Exception(e.LocalizedMessage ??
                                    e.Message ??
                                    e.GetType().Name, e);
            }

            HashOfLastStream = hashingStream.Hash;
            if (HashOfLastStream == null)
            {
                throw new Exception("hashing didn't work");                 //todo remove
            }
#else
            throw new Exception("Kdb is excluded with Key transform!");
#endif
        }
Пример #21
0
        public void Save(PwDatabase kpDatabase, Stream stream)
        {
            PwDatabaseV3 db       = new PwDatabaseV3();
            KcpPassword  pwd      = kpDatabase.MasterKey.GetUserKey <KcpPassword>();
            string       password = pwd != null?pwd.Password.ReadString() : "";

            KcpKeyFile keyfile         = kpDatabase.MasterKey.GetUserKey <KcpKeyFile>();
            Stream     keyfileContents = null;

            if (keyfile != null)
            {
                keyfileContents = new MemoryStream(keyfile.RawFileData.ReadData());
            }
            db.SetMasterKey(password, keyfileContents);

            AesKdf kdf = new AesKdf();

            if (!kdf.Uuid.Equals(kpDatabase.KdfParameters.KdfUuid))
            {
                db.NumRounds = (uint)PwDefs.DefaultKeyEncryptionRounds;
            }
            else
            {
                ulong uRounds = kpDatabase.KdfParameters.GetUInt64(
                    AesKdf.ParamRounds, PwDefs.DefaultKeyEncryptionRounds);
                uRounds = Math.Min(uRounds, 0xFFFFFFFEUL);

                db.NumRounds = (uint)uRounds;
            }


            db.Name = kpDatabase.Name;
            if (kpDatabase.DataCipherUuid.Equals(StandardAesEngine.AesUuid))
            {
                db.Algorithm = PwEncryptionAlgorithm.Rjindal;
            }
            else
            {
                db.Algorithm = PwEncryptionAlgorithm.Twofish;
            }

            //create groups
            db.Groups.Clear();
            var fromGroups = kpDatabase.RootGroup.GetGroups(true);
            Dictionary <int, PwGroupV3> groupV3s = new Dictionary <int, PwGroupV3>(fromGroups.Count());

            foreach (PwGroup g in fromGroups)
            {
                if (g == kpDatabase.RootGroup)
                {
                    continue;
                }
                PwGroupV3 groupV3 = ConvertGroup(g, db);
                db.Groups.Add(groupV3);
                groupV3s[groupV3.Id.Id] = groupV3;
            }

            //traverse again and assign parents
            db.RootGroup       = ConvertGroup(kpDatabase.RootGroup, db);
            db.RootGroup.Level = -1;

            AssignParent(kpDatabase.RootGroup, db, groupV3s);

            foreach (PwEntry e in kpDatabase.RootGroup.GetEntries(true))
            {
                PwEntryV3 entryV3 = ConvertEntry(e, db);
                entryV3.Parent = groupV3s[_groupData[e.ParentGroup.Uuid].Id];
                entryV3.Parent.ChildEntries.Add(entryV3);
                entryV3.GroupId = entryV3.Parent.Id.Id;
                db.Entries.Add(entryV3);
            }

            //add meta stream entries:
            if (db.Groups.Any())
            {
                foreach (var metaEntry in _metaStreams)
                {
                    metaEntry.GroupId = db.Groups.First().Id.Id;
                    db.Entries.Add(metaEntry);
                }
            }


            HashingStreamEx hashedStream = new HashingStreamEx(stream, true, null);
            PwDbV3Output    output       = new PwDbV3Output(db, hashedStream);

            output.Output();
            hashedStream.Close();
            HashOfLastStream = hashedStream.Hash;

            kpDatabase.HashOfLastIO = kpDatabase.HashOfFileOnDisk = HashOfLastStream;
            stream.Close();
        }