Advertisement
Shokedbrain

RSA signature pem files

Jun 26th, 2021
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.09 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Windows.Forms;
  4. using Chilkat;
  5.  
  6. namespace csharp_crypto_3
  7. {
  8. public partial class Form1 : Form
  9. {
  10. public Form1()
  11. {
  12. InitializeComponent();
  13. algBox.SelectedIndex = 0;
  14. }
  15.  
  16. private string SaveFile(string title, string filter)
  17. {
  18. var filePath = string.Empty;
  19. using (var dialog = new SaveFileDialog())
  20. {
  21. dialog.Filter = @filter;
  22. dialog.FilterIndex = 1;
  23. dialog.RestoreDirectory = true;
  24. dialog.Title = title;
  25. if (dialog.ShowDialog() == DialogResult.OK) filePath = dialog.FileName;
  26. }
  27.  
  28. return filePath;
  29. }
  30.  
  31. private string ReadFile(string title, string filter)
  32. {
  33. using (var dialog = new OpenFileDialog())
  34. {
  35. var content = string.Empty;
  36. dialog.Filter = @filter;
  37. dialog.FilterIndex = 1;
  38. dialog.RestoreDirectory = true;
  39. dialog.Title = @title;
  40. if (dialog.ShowDialog() != DialogResult.OK) return content;
  41. var fileStream = dialog.OpenFile();
  42. using (var reader = new StreamReader(fileStream))
  43. {
  44. content = reader.ReadToEnd();
  45. }
  46.  
  47. return content;
  48. }
  49. }
  50.  
  51. // вывод лога в RichTextBox
  52. private void Log(string output)
  53. {
  54. logBox.AppendText(output + "\r\n");
  55. logBox.ScrollToCaret();
  56. }
  57.  
  58. private void ActionButton_Click(object sender, EventArgs e)
  59. {
  60. logBox.Clear();
  61. var rsaLength = 0;
  62. var cont = true; // переменная, отвечающая за продолжение работы кода
  63. // проверка входных данных
  64. try
  65. {
  66. rsaLength = int.Parse(rsaLengthBox.Text);
  67. }
  68. catch (Exception ex)
  69. {
  70. Log(ex.Message);
  71. cont = false;
  72. }
  73.  
  74. if (cont)
  75. {
  76. // проверяем длину ключа
  77. if (rsaLength < 512 || rsaLength > 8192)
  78. {
  79. Log("Key length must be > 512 and < 8192");
  80. cont = false;
  81. }
  82. }
  83.  
  84. if (!cont) return; // завершаем работу функции при неверных входных данных
  85. // проверяем действие: подпись или проверка
  86. if (signRadioButton.Checked)
  87. {
  88. // подпись данных
  89. logBox.Clear();
  90. var rsa = new Rsa
  91. {
  92. LittleEndian = false,
  93. // порядок байтов
  94. // big endian
  95. // 0x1234 = 12 34
  96. // litle endian
  97. // 0x1234 = 34 12
  98. EncodingMode = "hex"
  99. };
  100. var success = rsa.GenerateKey(rsaLength);
  101. // Log(rsa_length.ToString());
  102. // выводим лог об успешном или нет завершении функции
  103. var hashedAlg = algBox.SelectedItem.ToString();
  104. Log("selected hash alg: " + hashedAlg);
  105. Log(success ? "Key has been successfully generated!" : rsa.LastErrorText);
  106.  
  107. Log("exporting private and public RSA keys...");
  108.  
  109. var publicXml = rsa.ExportPublicKey();
  110. var privateXml = rsa.ExportPrivateKey();
  111. var privateKey = new PrivateKey();
  112. var publicKey = new PublicKey();
  113.  
  114. // init savefiledialog
  115. // сохранение публичного и приватного ключа в pem file
  116. var privatePath = SaveFile("Save private key","PEM files (*.pem)|*.pem|All files (*.*)|*.*");
  117. var publicPath = SaveFile("Save public key", "PEM files (*.pem)|*.pem|All files (*.*)|*.*");
  118. success = privateKey.LoadXml(privateXml);
  119. Log(success? "private key has been loaded":"error while loading private key");
  120. success = publicKey.LoadXml(publicXml);
  121. Log(success ? "public key has been loaded" : "error while loading public key");
  122. // сохранения приватного и публичного ключа в отдельные файлы
  123. success = privateKey.SaveRsaPemFile(privatePath);
  124. if (!success)
  125. {
  126. Log("error has occurred while saving the file");
  127. return;
  128. }
  129.  
  130. Log("Private Key has been successfully saved in: ");
  131. Log(privatePath);
  132. success = publicKey.SaveOpenSslPemFile(publicPath);
  133. if (!success)
  134. {
  135. Log("error has occurred while saving the file");
  136. return;
  137. }
  138.  
  139. Log("Public Key has been successfully saved in: ");
  140. Log(publicPath);
  141.  
  142. // чтение исходного файла, данного для подписывания
  143. string toSignFile = ReadFile("Open file to sign", "All files (*.*)|*.*");
  144. Log(toSignFile);
  145.  
  146. // генерация подписи
  147. var hashed = rsa.SignStringENC(toSignFile, hashedAlg);
  148. var signed = SaveFile("Save signed doc", "All files (*.*)|*.*");
  149.  
  150. File.WriteAllText(signed, hashed);
  151. }
  152. else
  153. {
  154. logBox.Clear();
  155. // проверка подписи
  156. var rsa2 = new Rsa
  157. {
  158. LittleEndian = false
  159. }; // chilkat rsa
  160. var hashedAlg = algBox.SelectedItem.ToString();
  161. Log("selected hash alg: " + hashedAlg);
  162. var pubKey = new PublicKey();
  163. var toSignFile = ReadFile("Open file to sign", "All files (*.*)|*.*");
  164. var hashed = ReadFile("Open signed file","All files (*.*)|*.*");
  165. var filePublic = ReadFile("Open public key","PEM files (*.pem)|*.pem");
  166. var success = pubKey.LoadOpenSslPem(filePublic);
  167. Log(success ? "load public key file successfully" : "error");
  168. success = rsa2.ImportPublicKey(pubKey.GetXml());
  169.  
  170. rsa2.EncodingMode = "hex";
  171. success = rsa2.VerifyStringENC(toSignFile, hashedAlg, hashed);
  172. Log(rsa2.LastErrorText);
  173. //Log(success ? "Successful verification!" : rsa2.LastErrorText);
  174. }
  175. }
  176. }
  177. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement