コード例 #1
0
        private void decryptBtn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            CryptoKey key = keysLB.SelectedItem as CryptoKey;

            if (key.KeyPurpose == CryptoKey.Purpose.Encryption)
            {
                if (key.PublicOnly)
                {
                    Utils.ShowWarning("Для расшифрования файла необходимо иметь закрытый ключ");
                    return;
                }

                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Расшифровать файл...";
                if (ofd.ShowDialog().Value)
                {
                    string input = File.ReadAllText(ofd.FileName);
                    byte[] output;
                    try
                    {
                        output = Cryptography.E.GetBytes(Cryptography.Decrypt(input, key));
                    }
                    catch (Exception ex)
                    {
                        output = null;
                    }

                    if (output == null)
                    {
                        Utils.ShowError("Не удалось расшифровать файл");
                    }
                    else
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Title = "Сохранить расшифрованный файл...";
                        if (sfd.ShowDialog().Value)
                        {
                            File.WriteAllBytes(sfd.FileName, output);
                        }
                    }
                }
            }
            else if (key.KeyPurpose == CryptoKey.Purpose.Signature)
            {
                OpenFileDialog ofd1 = new OpenFileDialog();
                ofd1.Title = "Открыть файл для проверки подписи...";
                if (ofd1.ShowDialog().Value)
                {
                    OpenFileDialog ofd2 = new OpenFileDialog();
                    ofd2.Title      = "Открыть файл подписи...";
                    ofd2.DefaultExt = CryptoKey.DEFAULT_SIGNATURE_EXT;
                    if (ofd2.ShowDialog().Value)
                    {
                        byte[] input     = File.ReadAllBytes(ofd1.FileName);
                        string signature = File.ReadAllText(ofd2.FileName);
                        bool?  result;
                        try
                        {
                            result = Cryptography.Verify(Cryptography.E.GetString(input), signature, key);
                        }
                        catch (Exception ex)
                        {
                            result = null;
                        }

                        if (result == null)
                        {
                            Utils.ShowError("Не удалось проверить подпись файла");
                        }
                        else
                        {
                            if (result.Value)
                            {
                                Utils.ShowInfo("Файл успешно прошёл верификацию");
                            }
                            else
                            {
                                Utils.ShowError("Верификация не пройдена");
                            }
                        }
                    }
                }
            }
            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);
                }
            }
        }