コード例 #1
0
        // TODO: шифрование-дешифрование бинарных файлов заменяет некоторые байты на fdff
        private void encryptBtn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            CryptoKey key = keysLB.SelectedItem as CryptoKey;

            if (key.KeyPurpose == CryptoKey.Purpose.Encryption)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Зашифровать файл...";
                if (ofd.ShowDialog().Value)
                {
                    byte[] input  = File.ReadAllBytes(ofd.FileName);
                    string output = Cryptography.Encrypt(Cryptography.E.GetString(input), key);

                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Title = "Сохранить зашифрованный файл...";
                    if (sfd.ShowDialog().Value)
                    {
                        File.WriteAllText(sfd.FileName, output);
                    }
                }
            }
            else if (key.KeyPurpose == CryptoKey.Purpose.Signature)
            {
                if (key.PublicOnly)
                {
                    Utils.ShowWarning("Для создания подписи необходимо иметь закрытый ключ");
                    return;
                }

                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Подписать файл...";
                if (ofd.ShowDialog().Value)
                {
                    byte[] input  = File.ReadAllBytes(ofd.FileName);
                    string output = Cryptography.Sign(Cryptography.E.GetString(input), key);

                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Title      = "Сохранить подпись файла...";
                    sfd.DefaultExt = CryptoKey.DEFAULT_SIGNATURE_EXT;
                    if (sfd.ShowDialog().Value)
                    {
                        File.WriteAllText(sfd.FileName, output);
                    }
                }
            }
            else
            {
                throw new NotImplementedException("Как Вы здесь оказались?");
            }
        }
コード例 #2
0
        private void sendBtn_Click(object s, RoutedEventArgs e)
        {
            if (recipientsTB.Text.Trim().Length == 0)
            {
                Utils.ShowWarning("Укажите хотя бы один адрес в поле \"Получатели\"");
                return;
            }

            if (encryptChb.IsChecked.Value && encryptionCB.SelectedItem as CryptoKey == null)
            {
                Utils.ShowWarning("Выберите ключ шифрования из списка или снимите галочку");
                return;
            }

            if (signChb.IsChecked.Value && signatureCB.SelectedItem as CryptoKey == null)
            {
                Utils.ShowWarning("Выберите подпись из списка или снимите галочку");
                return;
            }

            string senderName = senderNameTB.Text.Trim();

            senderName = senderName.Length > 0 ? senderName : mailbox.Name;
            MailAddress sender = new MailAddress(mailbox.Address, senderName);

            using (MailMessage message = new MailMessage())
            {
                message.From = sender;
                message.To.Add(recipientsTB.Text);
                if (recipientsCcTB.Text.Trim().Length > 0)
                {
                    message.CC.Add(recipientsCcTB.Text);
                }
                if (recipientsBccTB.Text.Trim().Length > 0)
                {
                    message.Bcc.Add(recipientsBccTB.Text);
                }
                message.Subject = subjectTB.Text.Length > 0 ? subjectTB.Text : "Без темы";

                if (KeyToDeliver != null)
                {
                    message.Headers.Add(Cryptography.KEY_DELIVERY_HEADER, "public");

                    string filename = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "tcr-public.key");
                    KeyToDeliver.SerializeToFile(filename);
                    AttachFile(filename);

                    string purpuse;
                    if (KeyToDeliver.KeyPurpose == CryptoKey.Purpose.Encryption)
                    {
                        purpuse = "для шифрования";
                    }
                    else if (KeyToDeliver.KeyPurpose == CryptoKey.Purpose.Signature)
                    {
                        purpuse = "для верификации цифровой подписи";
                    }
                    else
                    {
                        throw new NotImplementedException("Как Вы здесь оказались?");
                    }

                    string ownerMatch;
                    if (KeyToDeliver.OwnerAddress.Equals(mailbox.Address))
                    {
                        ownerMatch = "<span style=\"color: " + Utils.ColorToHexString(Colors.Green) +
                                     "\">ключ принадлежит отправителю</span>";
                    }
                    else
                    {
                        ownerMatch = "<span style=\"color: " + Utils.ColorToHexString(Colors.DarkOrange) +
                                     "\">не совпадает с адресом отправителя</span>";
                    }

                    StringBuilder body = new StringBuilder();
                    body.Append("Это письмо содержит открытый ключ " + purpuse + "<br>");
                    body.Append("Адрес владельца ключа: " + KeyToDeliver.OwnerAddress + " - " + ownerMatch + "<br>");
                    body.Append("Дата и время создания ключа: " + KeyToDeliver.DateTime + "<br>");
                    body.Append("<br>");
                    body.Append("Приймите запрос в The Crypto, чтобы добавить этот ключ в Вашу библиотеку ключей");
                    bodyHtmlEditor.ContentHtml = body.ToString();
                }
                message.Body = "<html><meta charset=\"" + App.HTML_CHARSET + "\"><body>" + bodyHtmlEditor.ContentHtml + "</body></html>";

                CryptoKey signatureKey = signatureCB.SelectedItem as CryptoKey;
                if (signatureKey != null)
                {
                    string signature = Cryptography.Sign(message.Body, signatureKey);
                    message.Headers.Add(Cryptography.SIGNATURE_ID_HEADER, signatureKey.Id);
                    message.Headers.Add(Cryptography.SIGNATURE_HEADER, signature);
                }

                CryptoKey encryptionKey = encryptionCB.SelectedItem as CryptoKey;
                if (encryptionKey != null)
                {
                    message.Body = Cryptography.Encrypt(message.Body, encryptionKey);
                    message.Headers.Add(Cryptography.ENCRYPTION_ID_HEADER, encryptionKey.Id);
                }

                message.IsBodyHtml = true;
                foreach (FileInfo f in attachmentsPanel.Items)
                {
                    message.Attachments.Add(new Attachment(f.FullName));
                }

                try
                {
                    using (SmtpClient smtp = new SmtpClient(mailbox.SmtpDomain, mailbox.SmtpPort))
                    {
                        smtp.Credentials = new NetworkCredential(mailbox.Address, mailbox.Password);
                        smtp.EnableSsl   = useSsl;
                        smtp.Send(message);
                    }
                    Close();
                }
                catch (Exception ex)
                {
                    Utils.ShowError(ex.Message);
                }
            }
        }