Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Windows.Forms;
- using Chilkat;
- namespace csharp_crypto_3
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- algBox.SelectedIndex = 0;
- }
- private string SaveFile(string title, string filter)
- {
- var filePath = string.Empty;
- using (var dialog = new SaveFileDialog())
- {
- dialog.Filter = @filter;
- dialog.FilterIndex = 1;
- dialog.RestoreDirectory = true;
- dialog.Title = title;
- if (dialog.ShowDialog() == DialogResult.OK) filePath = dialog.FileName;
- }
- return filePath;
- }
- private string ReadFile(string title, string filter)
- {
- using (var dialog = new OpenFileDialog())
- {
- var content = string.Empty;
- dialog.Filter = @filter;
- dialog.FilterIndex = 1;
- dialog.RestoreDirectory = true;
- dialog.Title = @title;
- if (dialog.ShowDialog() != DialogResult.OK) return content;
- var fileStream = dialog.OpenFile();
- using (var reader = new StreamReader(fileStream))
- {
- content = reader.ReadToEnd();
- }
- return content;
- }
- }
- // вывод лога в RichTextBox
- private void Log(string output)
- {
- logBox.AppendText(output + "\r\n");
- logBox.ScrollToCaret();
- }
- private void ActionButton_Click(object sender, EventArgs e)
- {
- logBox.Clear();
- var rsaLength = 0;
- var cont = true; // переменная, отвечающая за продолжение работы кода
- // проверка входных данных
- try
- {
- rsaLength = int.Parse(rsaLengthBox.Text);
- }
- catch (Exception ex)
- {
- Log(ex.Message);
- cont = false;
- }
- if (cont)
- {
- // проверяем длину ключа
- if (rsaLength < 512 || rsaLength > 8192)
- {
- Log("Key length must be > 512 and < 8192");
- cont = false;
- }
- }
- if (!cont) return; // завершаем работу функции при неверных входных данных
- // проверяем действие: подпись или проверка
- if (signRadioButton.Checked)
- {
- // подпись данных
- logBox.Clear();
- var rsa = new Rsa
- {
- LittleEndian = false,
- // порядок байтов
- // big endian
- // 0x1234 = 12 34
- // litle endian
- // 0x1234 = 34 12
- EncodingMode = "hex"
- };
- var success = rsa.GenerateKey(rsaLength);
- // Log(rsa_length.ToString());
- // выводим лог об успешном или нет завершении функции
- var hashedAlg = algBox.SelectedItem.ToString();
- Log("selected hash alg: " + hashedAlg);
- Log(success ? "Key has been successfully generated!" : rsa.LastErrorText);
- Log("exporting private and public RSA keys...");
- var publicXml = rsa.ExportPublicKey();
- var privateXml = rsa.ExportPrivateKey();
- var privateKey = new PrivateKey();
- var publicKey = new PublicKey();
- // init savefiledialog
- // сохранение публичного и приватного ключа в pem file
- var privatePath = SaveFile("Save private key","PEM files (*.pem)|*.pem|All files (*.*)|*.*");
- var publicPath = SaveFile("Save public key", "PEM files (*.pem)|*.pem|All files (*.*)|*.*");
- success = privateKey.LoadXml(privateXml);
- Log(success? "private key has been loaded":"error while loading private key");
- success = publicKey.LoadXml(publicXml);
- Log(success ? "public key has been loaded" : "error while loading public key");
- // сохранения приватного и публичного ключа в отдельные файлы
- success = privateKey.SaveRsaPemFile(privatePath);
- if (!success)
- {
- Log("error has occurred while saving the file");
- return;
- }
- Log("Private Key has been successfully saved in: ");
- Log(privatePath);
- success = publicKey.SaveOpenSslPemFile(publicPath);
- if (!success)
- {
- Log("error has occurred while saving the file");
- return;
- }
- Log("Public Key has been successfully saved in: ");
- Log(publicPath);
- // чтение исходного файла, данного для подписывания
- string toSignFile = ReadFile("Open file to sign", "All files (*.*)|*.*");
- Log(toSignFile);
- // генерация подписи
- var hashed = rsa.SignStringENC(toSignFile, hashedAlg);
- var signed = SaveFile("Save signed doc", "All files (*.*)|*.*");
- File.WriteAllText(signed, hashed);
- }
- else
- {
- logBox.Clear();
- // проверка подписи
- var rsa2 = new Rsa
- {
- LittleEndian = false
- }; // chilkat rsa
- var hashedAlg = algBox.SelectedItem.ToString();
- Log("selected hash alg: " + hashedAlg);
- var pubKey = new PublicKey();
- var toSignFile = ReadFile("Open file to sign", "All files (*.*)|*.*");
- var hashed = ReadFile("Open signed file","All files (*.*)|*.*");
- var filePublic = ReadFile("Open public key","PEM files (*.pem)|*.pem");
- var success = pubKey.LoadOpenSslPem(filePublic);
- Log(success ? "load public key file successfully" : "error");
- success = rsa2.ImportPublicKey(pubKey.GetXml());
- rsa2.EncodingMode = "hex";
- success = rsa2.VerifyStringENC(toSignFile, hashedAlg, hashed);
- Log(rsa2.LastErrorText);
- //Log(success ? "Successful verification!" : rsa2.LastErrorText);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement