This commit is contained in:
Данила Селяев 2023-05-20 00:18:29 +04:00
parent 2d609f55c0
commit 907b6ddaba
12 changed files with 588 additions and 133 deletions

View File

@ -9,7 +9,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Contracts", "Contracts\Cont
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataModels", "DataModels\DataModels.csproj", "{9D413173-A515-4364-A9DD-FE8923D50816}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileImplements", "FileImplements\FileImplements.csproj", "{D72DB056-4D7C-48BB-A562-ACEF385472FF}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FileImplements", "FileImplements\FileImplements.csproj", "{D72DB056-4D7C-48BB-A562-ACEF385472FF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BuisnessLogic", "BuisnessLogic\BuisnessLogic.csproj", "{20B92398-7E97-4D43-A54D-4584474C8CC6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -33,6 +35,10 @@ Global
{D72DB056-4D7C-48BB-A562-ACEF385472FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D72DB056-4D7C-48BB-A562-ACEF385472FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D72DB056-4D7C-48BB-A562-ACEF385472FF}.Release|Any CPU.Build.0 = Release|Any CPU
{20B92398-7E97-4D43-A54D-4584474C8CC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{20B92398-7E97-4D43-A54D-4584474C8CC6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{20B92398-7E97-4D43-A54D-4584474C8CC6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{20B92398-7E97-4D43-A54D-4584474C8CC6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -19,8 +19,10 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BuisnessLogic\BuisnessLogic.csproj" />
<ProjectReference Include="..\Contracts\Contracts.csproj" />
<ProjectReference Include="..\DataModels\DataModels.csproj" />
<ProjectReference Include="..\FileImplements\FileImplements.csproj" />
</ItemGroup>
</Project>

View File

@ -12,42 +12,21 @@ using Org.BouncyCastle.X509;
public static class Engine
{
private static readonly string keyPairPath = @"G:\tests\rsaKeyPair.pem";
private static readonly string privateKeyPath = @"G:\tests\rsaPrivateKey.pem";
private static readonly string publicKeyPath = @"G:\tests\rsaPublicKey.pem";
private static readonly string csrPath = @"G:\tests\rsaCSR.pem";
private static readonly string signedCertPath = @"G:\tests\rsaSignedCert.pem";
private static readonly string selfSignedCertPath = @"G:\tests\selfSignedCert.pem";
private static readonly string privateCertPath = @"G:\tests\privateCert.pfx";
private static readonly string privateCertPass = "1234";
/// <summary>
/// Эта тестовая функция может генерировать пару открытых и закрытых ключей с использованием алгоритма шифрования RSA.
/// Это широко используемый алгоритм для генерации защищенных ключей, который часто используется для защищенной связи.
/// </summary>
public static void GenerateRSAKeyPair()
public static void GenerateRSAKeyPair(string keyPairPath)
{
var keyPair = Cryptography.GenerateRSAKeyPair();
keyPair.ToPemFile(keyPairPath);
MessageBox.Show("OK");
}
/// <summary>
/// Эта тестовая функция может генерировать пару открытых и закрытых ключей с использованием алгоритма шифрования ECDSA.
/// Это широко используемый алгоритм для генерации защищенных ключей, который часто используется для защищенной связи.s
/// </summary>
public static void GenerateECDSAKeyPair()
{
var keyPair = Cryptography.GenerateECDSAKeyPair();
keyPair.ToPemFile(keyPairPath);
}
/// <summary>
/// Этой тестовой функцией может быть запись пары ключей в файл или создание закрытого и открытого ключей.
/// Закрытые ключи используются в асимметричном шифровании, где один ключ используется для шифрования, а другой - для дешифрования.
/// </summary>
public static void WriteKeyPairInPemFile()
public static void WriteKeyPairInPemFile(string keyPairPath, string privateKeyPath, string publicKeyPath)
{
var keyPair = keyPairPath.GetKeyPairFromPem();
keyPair.Private.ToPemFile(privateKeyPath);
@ -57,7 +36,7 @@ public static class Engine
/// <summary>
/// Эта тестовая функция может генерировать запрос на подпись сертификата (CSR), который представляет собой сообщение, отправляемое в центр сертификации для запроса цифрового сертификата.
/// </summary>
public static void GenerateCSR()
public static void GenerateCSR(string keyPairPath, string csrPath)
{
var keyPair = keyPairPath.GetKeyPairFromPem();
var csr = Cryptography.GenerateCSR("Russia", "Ulyanovsk region", "Ulyanovsk", "UISTU", "Student", "Seliaev_D.A", CryptographyAlgorithm.SHA256withRSA, keyPair);
@ -68,7 +47,7 @@ public static class Engine
/// Эта тестовая функция может генерировать самозаверяющий сертификат.
/// Самозаверяющие сертификаты - это цифровые сертификаты, подписанные тем же лицом, которое выдает сертификат.
/// </summary>
public static void GenerateSelfSignedCert()
public static void GenerateSelfSignedCert(string csrPath, string keyPairPath, string selfSignedCertPath)
{
var selfSignedCert = Cryptography.GenerateSelfSignedCert(csrPath.GetCSRPemFile(),
keyPairPath.GetPrivateKeyFromPem(),
@ -80,7 +59,7 @@ public static class Engine
/// <summary>
/// Этой тестовой функцией может быть создание файла PFX, который представляет собой формат файла, используемый для безопасного хранения закрытых ключей и сертификатов.
/// </summary>
public static void CreatePfx()
public static void CreatePfx(string keyPairPath, string selfSignedCertPath, string privateCertPath)
{
var certificate = new X509Certificate2(selfSignedCertPath);
var keyPair = keyPairPath.GetKeyPairFromPem();
@ -106,7 +85,7 @@ public static class Engine
/// Эта тестовая функция может генерировать подписанный сертификат.
/// Подписанный сертификат - это цифровой сертификат, который был подписан доверенной третьей стороной, известной как центр сертификации.
/// </summary>
public static void GenerateSignedCert()
public static void GenerateSignedCert(string csrPath, string privateCertPath, string privateCertPass, string signedCertPath)
{
var signedCert = Cryptography.GenerateSignedCertificate(csrPath.GetCSRPemFile(),
privateCertPath.GetPrivateCert(privateCertPass),
@ -119,7 +98,7 @@ public static class Engine
/// <summary>
/// Эта тестовая функция может проверять, что сертификат был подписан закрытым ключом.
/// </summary>
public static void VerifySignedByPrivateKey()
public static void VerifySignedByPrivateKey(string privateKeyPath, string publicKeyPath)
{
var message = "Hello world";
var signature = Cryptography.SignDataByPrivateKey(message, privateKeyPath.GetPrivateKeyFromPem());
@ -132,7 +111,7 @@ public static class Engine
//Эта тестовая функция может расшифровывать данные с использованием закрытого ключа.
public static void TestDecryptWithKey()
public static void TestDecryptWithKey(string keyPairPath)
{
var message = "Hello world";
var keyPair = keyPairPath.GetKeyPairFromPem();
@ -144,7 +123,7 @@ public static class Engine
/// <summary>
/// Эта тестовая функция может проверять, что подписанным данным можно доверять, используя тот же сертификат.
/// </summary>
public static void TestVerifySignedDataBySameCert()
public static void TestVerifySignedDataBySameCert(string privateCertPath, string privateCertPass)
{
var message = "Hello world";
var signature = Cryptography.SignDataByPrivateCert(message, privateCertPath.GetPrivateCert(privateCertPass));
@ -163,13 +142,13 @@ public static class Engine
/// <summary>
///Эта тестовая функция может проверять соответствие открытого ключа и закрытого ключа.
/// </summary>
public static void VerifyMatchBetweenPublicAndPrivateKeys()
public static void VerifyMatchBetweenPublicAndPrivateKeys(string signedCertPath, string privateCertPath, string privateCertPass)
{
var isValid = Cryptography.VerifyMatchBetweenPublicAndPrivateKeys(signedCertPath.GetPublicCert(), privateCertPath.GetPrivateCert(privateCertPass));
if(isValid) MessageBox.Show("Ключи совпадают");
}
// шифровка разшифровка
public static void check()
public static void check(string signedCertPath, string privateCertPath, string privateCertPass)
{
var message = "Hello world";
var encoded = Cryptography.EncryptDataByPublicCert(message, signedCertPath.GetPublicCert());
@ -177,27 +156,4 @@ public static class Engine
MessageBox.Show(Encoding.UTF8.GetString(data));
}
/// <summary>
/// Проверяет метод Get Compressed ECDSA PublicKey FromBase64, предоставляя сжатый открытый ключ ECDSA в кодировке Base64
/// и проверяем, не является ли полученный ключ закрытым.
/// </summary>
public static void TestGetCompressedECDSAPublicKeyFromBase64()
{
var key = "A2srIPKCMgOVyXq/fhK5Wnr3A/w9cfDv7dEepWZAKglw".GetCompressedECDSAPublicKeyFromBase64();
Console.WriteLine(!key.IsPrivate);
}
/// <summary>
/// Проверяет, получают ли они метод compressedecdsapublickeyfrompem, предоставляя сжатый открытый ключ ECDSA в формате PEM
/// и проверяем, не является ли импортированный ключ закрытым..
/// </summary>
public static void TestImportCompressedECDSAPublicKeyFromPem()
{
var compressedKeyAsPem = @"-----BEGIN EC PUBLIC KEY-----A2srIPKCMgOVyXq/fhK5Wnr3A/w9cfDv7dEepWZAKglw-----END EC PUBLIC KEY-----";
var key = compressedKeyAsPem.GetCompressedECDSAPublicKeyFromPem();
Console.WriteLine(!key.IsPrivate);
}
}

View File

@ -30,7 +30,6 @@
{
buttonKeyCreate = new Button();
dataGridViewKeys = new DataGridView();
ButtonKeyRemove = new Button();
buttonKeysUpdate = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewKeys).BeginInit();
SuspendLayout();
@ -54,23 +53,15 @@
dataGridViewKeys.Size = new Size(423, 435);
dataGridViewKeys.TabIndex = 1;
//
// ButtonKeyRemove
//
ButtonKeyRemove.Location = new Point(441, 52);
ButtonKeyRemove.Name = "ButtonKeyRemove";
ButtonKeyRemove.Size = new Size(128, 34);
ButtonKeyRemove.TabIndex = 2;
ButtonKeyRemove.Text = "Удалить";
ButtonKeyRemove.UseVisualStyleBackColor = true;
//
// buttonKeysUpdate
//
buttonKeysUpdate.Location = new Point(441, 92);
buttonKeysUpdate.Location = new Point(441, 52);
buttonKeysUpdate.Name = "buttonKeysUpdate";
buttonKeysUpdate.Size = new Size(128, 34);
buttonKeysUpdate.TabIndex = 3;
buttonKeysUpdate.Text = "Обновить";
buttonKeysUpdate.UseVisualStyleBackColor = true;
buttonKeysUpdate.Click += buttonKeysUpdate_Click;
//
// FormKeys
//
@ -78,7 +69,6 @@
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(581, 459);
Controls.Add(buttonKeysUpdate);
Controls.Add(ButtonKeyRemove);
Controls.Add(dataGridViewKeys);
Controls.Add(buttonKeyCreate);
Name = "FormKeys";
@ -91,7 +81,6 @@
private Button buttonKeyCreate;
private DataGridView dataGridViewKeys;
private Button ButtonKeyRemove;
private Button buttonKeysUpdate;
}
}

View File

@ -1,4 +1,5 @@
using Contracts.BusinessLogicsContracts;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using DataModels.Models;
using ElectronicSignature.Certification;
@ -35,9 +36,85 @@ namespace AppView
private void buttonKeyCreate_Click(object sender, EventArgs e)
{
var keyPair = Cryptography.GenerateRSAKeyPair();
keyPair.ToPemFile(keyPairPath);
try
{
keyPair.ToPemFile(keyPairPath);
var model = new KeyBindingModel
{
Id = _id ?? 0,
Name = "KeyPair",
Path = keyPairPath,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Пара создана");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения пары ключей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
keyPair = keyPairPath.GetKeyPairFromPem();
try
{
keyPair.Private.ToPemFile(privateKeyPath);
var model = new KeyBindingModel
{
Id = _id ?? 0,
Name = "PrivateKey",
Path = privateKeyPath,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Закрыиый ключ создан");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try{
keyPair.Public.ToPemFile(publicKeyPath);
var model = new KeyBindingModel
{
Id = _id ?? 0,
Name = "PublicKey",
Path = publicKeyPath,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Открытый ключ создан");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//проверка ключей
Engine.VerifyMatchBetweenPublicAndPrivateKeys(signedCertPath, privateCertPath, privateCertPass);
//запросы и сертификаты
Engine.GenerateCSR(keyPairPath, csrPath);//csr запрос
Engine.GenerateSelfSignedCert(csrPath, keyPairPath, selfSignedCertPath);//само-подписанный сертификат
Engine.CreatePfx(keyPairPath, selfSignedCertPath, privateCertPath);//закрытый сертификат
Engine.GenerateSignedCert( csrPath, privateCertPath, privateCertPass, signedCertPath);//подписанный сертификат
MessageBox.Show("Ключи созданы");
LoadData();
}
private void FormFood_Load(object sender, EventArgs e)
@ -86,5 +163,11 @@ namespace AppView
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonKeysUpdate_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -39,19 +39,31 @@
ключиToolStripMenuItem = new ToolStripMenuItem();
rSAToolStripMenuItem = new ToolStripMenuItem();
eCDSAToolStripMenuItem = new ToolStripMenuItem();
groupBoxFile = new GroupBox();
menuStrip1 = new MenuStrip();
ключиToolStripMenuItem1 = new ToolStripMenuItem();
создатьToolStripMenuItem = new ToolStripMenuItem();
списокToolStripMenuItem = new ToolStripMenuItem();
groupBoxFile.SuspendLayout();
textBoxPass = new TextBox();
label3 = new Label();
buttonSavepath = new Button();
textBoxSavePath = new TextBox();
label4 = new Label();
label5 = new Label();
label6 = new Label();
textBoxKey2 = new TextBox();
textBoxFile2 = new TextBox();
groupBox1 = new GroupBox();
groupBox2 = new GroupBox();
buttonCert2 = new Button();
buttonFile2 = new Button();
menuStrip1.SuspendLayout();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(40, 45);
label1.Location = new Point(6, 26);
label1.Name = "label1";
label1.Size = new Size(36, 15);
label1.TabIndex = 0;
@ -60,29 +72,29 @@
// label2
//
label2.AutoSize = true;
label2.Location = new Point(40, 85);
label2.Location = new Point(6, 59);
label2.Name = "label2";
label2.Size = new Size(38, 15);
label2.Size = new Size(131, 15);
label2.TabIndex = 1;
label2.Text = "Ключ";
label2.Text = "Открытый сертификат";
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(98, 42);
textBoxFilePath.Location = new Point(143, 23);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.Size = new Size(337, 23);
textBoxFilePath.Size = new Size(269, 23);
textBoxFilePath.TabIndex = 2;
//
// textBoxKeyPath
//
textBoxKeyPath.Location = new Point(98, 82);
textBoxKeyPath.Location = new Point(143, 56);
textBoxKeyPath.Name = "textBoxKeyPath";
textBoxKeyPath.Size = new Size(337, 23);
textBoxKeyPath.Size = new Size(269, 23);
textBoxKeyPath.TabIndex = 3;
//
// buttonFilePath
//
buttonFilePath.Location = new Point(441, 42);
buttonFilePath.Location = new Point(418, 22);
buttonFilePath.Name = "buttonFilePath";
buttonFilePath.Size = new Size(75, 23);
buttonFilePath.TabIndex = 4;
@ -92,7 +104,7 @@
//
// buttonKeyPath
//
buttonKeyPath.Location = new Point(441, 82);
buttonKeyPath.Location = new Point(418, 56);
buttonKeyPath.Name = "buttonKeyPath";
buttonKeyPath.Size = new Size(75, 23);
buttonKeyPath.TabIndex = 5;
@ -102,7 +114,7 @@
//
// buttonWriteKey
//
buttonWriteKey.Location = new Point(6, 22);
buttonWriteKey.Location = new Point(6, 123);
buttonWriteKey.Name = "buttonWriteKey";
buttonWriteKey.Size = new Size(163, 48);
buttonWriteKey.TabIndex = 6;
@ -112,7 +124,7 @@
//
// buttonCheckKey
//
buttonCheckKey.Location = new Point(248, 22);
buttonCheckKey.Location = new Point(0, 152);
buttonCheckKey.Name = "buttonCheckKey";
buttonCheckKey.Size = new Size(163, 48);
buttonCheckKey.TabIndex = 7;
@ -135,66 +147,177 @@
eCDSAToolStripMenuItem.Name = "eCDSAToolStripMenuItem";
eCDSAToolStripMenuItem.Size = new Size(32, 19);
//
// groupBoxFile
//
groupBoxFile.Controls.Add(buttonWriteKey);
groupBoxFile.Controls.Add(buttonCheckKey);
groupBoxFile.Location = new Point(73, 141);
groupBoxFile.Name = "groupBoxFile";
groupBoxFile.Size = new Size(417, 86);
groupBoxFile.TabIndex = 10;
groupBoxFile.TabStop = false;
groupBoxFile.Text = "Документы";
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { ключиToolStripMenuItem1 });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(568, 24);
menuStrip1.Size = new Size(542, 24);
menuStrip1.TabIndex = 11;
menuStrip1.Text = "menuStrip1";
//
// ключиToolStripMenuItem1
//
ключиToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { создатьToolStripMenuItem, списокToolStripMenuItem });
ключиToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { списокToolStripMenuItem });
ключиToolStripMenuItem1.Name = "ключиToolStripMenuItem1";
ключиToolStripMenuItem1.Size = new Size(57, 20);
ключиToolStripMenuItem1.Text = "Ключи";
//
// создатьToolStripMenuItem
//
создатьToolStripMenuItem.Name = "создатьToolStripMenuItem";
создатьToolStripMenuItem.Size = new Size(180, 22);
создатьToolStripMenuItem.Text = "Создать";
создатьToolStripMenuItem.Click += создатьToolStripMenuItem_Click;
//
// списокToolStripMenuItem
//
списокToolStripMenuItem.Name = "списокToolStripMenuItem";
списокToolStripMenuItem.Size = new Size(180, 22);
списокToolStripMenuItem.Size = new Size(115, 22);
списокToolStripMenuItem.Text = "Список";
списокToolStripMenuItem.Click += списокToolStripMenuItem_Click;
//
// textBoxPass
//
textBoxPass.Location = new Point(160, 105);
textBoxPass.Name = "textBoxPass";
textBoxPass.Size = new Size(246, 23);
textBoxPass.TabIndex = 12;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(6, 108);
label3.Name = "label3";
label3.Size = new Size(49, 15);
label3.TabIndex = 13;
label3.Text = "Пароль";
//
// buttonSavepath
//
buttonSavepath.Location = new Point(418, 86);
buttonSavepath.Name = "buttonSavepath";
buttonSavepath.Size = new Size(75, 23);
buttonSavepath.TabIndex = 14;
buttonSavepath.Text = "Выбрать";
buttonSavepath.UseVisualStyleBackColor = true;
buttonSavepath.Click += buttonSavepath_Click;
//
// textBoxSavePath
//
textBoxSavePath.Location = new Point(143, 85);
textBoxSavePath.Name = "textBoxSavePath";
textBoxSavePath.Size = new Size(269, 23);
textBoxSavePath.TabIndex = 15;
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(6, 89);
label4.Name = "label4";
label4.Size = new Size(101, 15);
label4.TabIndex = 16;
label4.Text = "Путь сохранения";
//
// label5
//
label5.AutoSize = true;
label5.Location = new Point(6, 69);
label5.Name = "label5";
label5.Size = new Size(130, 15);
label5.TabIndex = 17;
label5.Text = "Закрытый сертификат";
//
// label6
//
label6.AutoSize = true;
label6.Location = new Point(6, 35);
label6.Name = "label6";
label6.Size = new Size(36, 15);
label6.TabIndex = 18;
label6.Text = "Файл";
//
// textBoxKey2
//
textBoxKey2.Location = new Point(160, 69);
textBoxKey2.Name = "textBoxKey2";
textBoxKey2.Size = new Size(246, 23);
textBoxKey2.TabIndex = 19;
//
// textBoxFile2
//
textBoxFile2.Location = new Point(160, 35);
textBoxFile2.Name = "textBoxFile2";
textBoxFile2.Size = new Size(246, 23);
textBoxFile2.TabIndex = 20;
//
// groupBox1
//
groupBox1.Controls.Add(label1);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label4);
groupBox1.Controls.Add(textBoxFilePath);
groupBox1.Controls.Add(textBoxKeyPath);
groupBox1.Controls.Add(buttonWriteKey);
groupBox1.Controls.Add(buttonSavepath);
groupBox1.Controls.Add(textBoxSavePath);
groupBox1.Controls.Add(buttonFilePath);
groupBox1.Controls.Add(buttonKeyPath);
groupBox1.Location = new Point(12, 27);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(513, 191);
groupBox1.TabIndex = 21;
groupBox1.TabStop = false;
groupBox1.Text = "Проверка подписи";
//
// groupBox2
//
groupBox2.Controls.Add(buttonCert2);
groupBox2.Controls.Add(buttonFile2);
groupBox2.Controls.Add(label6);
groupBox2.Controls.Add(label5);
groupBox2.Controls.Add(textBoxPass);
groupBox2.Controls.Add(buttonCheckKey);
groupBox2.Controls.Add(textBoxKey2);
groupBox2.Controls.Add(textBoxFile2);
groupBox2.Controls.Add(label3);
groupBox2.Location = new Point(18, 224);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(507, 222);
groupBox2.TabIndex = 22;
groupBox2.TabStop = false;
groupBox2.Text = "groupBox2";
//
// buttonCert2
//
buttonCert2.Location = new Point(412, 69);
buttonCert2.Name = "buttonCert2";
buttonCert2.Size = new Size(75, 23);
buttonCert2.TabIndex = 22;
buttonCert2.Text = "Выбрать";
buttonCert2.UseVisualStyleBackColor = true;
buttonCert2.Click += buttonCert2_Click;
//
// buttonFile2
//
buttonFile2.Location = new Point(412, 35);
buttonFile2.Name = "buttonFile2";
buttonFile2.Size = new Size(75, 23);
buttonFile2.TabIndex = 21;
buttonFile2.Text = "Выбрать";
buttonFile2.UseVisualStyleBackColor = true;
buttonFile2.Click += buttonFile2_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(568, 242);
ClientSize = new Size(542, 474);
Controls.Add(groupBox2);
Controls.Add(groupBox1);
Controls.Add(menuStrip1);
Controls.Add(groupBoxFile);
Controls.Add(buttonKeyPath);
Controls.Add(buttonFilePath);
Controls.Add(textBoxKeyPath);
Controls.Add(textBoxFilePath);
Controls.Add(label2);
Controls.Add(label1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "ЭЦП";
groupBoxFile.ResumeLayout(false);
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -212,10 +335,22 @@
private ToolStripMenuItem ключиToolStripMenuItem;
private ToolStripMenuItem rSAToolStripMenuItem;
private ToolStripMenuItem eCDSAToolStripMenuItem;
private GroupBox groupBoxFile;
private MenuStrip menuStrip1;
private ToolStripMenuItem ключиToolStripMenuItem1;
private ToolStripMenuItem создатьToolStripMenuItem;
private ToolStripMenuItem списокToolStripMenuItem;
private TextBox textBoxPass;
private Label label3;
private Button buttonSavepath;
private TextBox textBoxSavePath;
private Label label4;
private Label label5;
private Label label6;
private TextBox textBoxKey2;
private TextBox textBoxFile2;
private GroupBox groupBox1;
private GroupBox groupBox2;
private Button buttonCert2;
private Button buttonFile2;
}
}

View File

@ -2,6 +2,7 @@ using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;
using ElectronicSignature.Certification;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
@ -18,36 +19,89 @@ namespace AppView
}
private void buttonFilePath_Click(object sender, EventArgs e)
{
using var dialog = new OpenFileDialog { };
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxFilePath.Text = dialog.FileName;
}
}
private void buttonSavepath_Click(object sender, EventArgs e)
{
using var dialog = new OpenFileDialog { };
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxSavePath.Text = dialog.FileName;
}
}
private void buttonKeyPath_Click(object sender, EventArgs e)
{
using var dialog = new OpenFileDialog { Filter = "pem|*.pem" };
using var dialog = new OpenFileDialog { };
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxKeyPath.Text = dialog.FileName;
}
}
private void buttonFile2_Click(object sender, EventArgs e)
{
using var dialog = new OpenFileDialog { };
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxFile2.Text = dialog.FileName;
}
}
private void buttonCert2_Click(object sender, EventArgs e)
{
using var dialog = new OpenFileDialog { };
if (dialog.ShowDialog() == DialogResult.OK)
{
textBoxKey2.Text = dialog.FileName;
}
}
private void buttonWriteKey_Click(object sender, EventArgs e)
{
FileStream? fstream = null;
try
{
fstream = File.OpenRead(textBoxFilePath.Text);
var encoded = Cryptography.EncryptDataByPublicCert(fstream.ToString(), textBoxKeyPath.Text.GetPublicCert());
fstream?.Close();
fstream = new FileStream(textBoxSavePath.Text, FileMode.OpenOrCreate);
fstream?.Write(encoded);
fstream?.Close();
MessageBox.Show("Óñïåõ");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCheckKey_Click(object sender, EventArgs e)
{
}
private void buttonGenerateKeyRSA_Click(object sender, EventArgs e)
{
}
private void ñîçäàòüToolStripMenuItem_Click(object sender, EventArgs e)
{
var keyPair = Cryptography.GenerateRSAKeyPair();
keyPair.ToPemFile(keyPairPath);
MessageBox.Show("Êëþ÷è ñîçäàíû");
FileStream? fstream = null;
try
{
fstream = new FileStream(textBoxFile2.Text, FileMode.Open);
var privateCertPath = textBoxKey2.Text;
var signature = Cryptography.SignDataByPrivateCert(fstream.ToString(), privateCertPath.GetPrivateCert(textBoxPass.Text));
if (Cryptography.VerifySignedDataByCertIssuer(signature, textBoxKeyPath.Text.GetPublicCert(), out var data))
{
if (data != null)
MessageBox.Show(Encoding.UTF8.GetString(data));
}
else
{
MessageBox.Show("False");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ñïèñîêToolStripMenuItem_Click(object sender, EventArgs e)
@ -59,5 +113,6 @@ namespace AppView
form.ShowDialog();
}
}
}
}

View File

@ -1,5 +1,7 @@
using BuisnessLogic.BuisnessLogic;
using Contracts.BusinessLogicsContracts;
using Contracts.StoragesContracts;
using FileImplements.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
@ -27,6 +29,12 @@ namespace AppView
option.AddNLog("nlog.config");
});
services.AddTransient<IKeyStorage, KeyStorage>();
services.AddTransient<ICertStorage, CertStorage>();
services.AddTransient<IKeyLogic, KeyLogic>();
services.AddTransient<ICertLogic, CertLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormKeys>();
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Contracts\Contracts.csproj" />
<ProjectReference Include="..\DataModels\DataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,105 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
namespace BuisnessLogic.BuisnessLogic
{
public class CertLogic : ICertLogic
{
private readonly ICertStorage _certStorage;
public CertLogic(ICertStorage foodStorage)
{
_certStorage = foodStorage;
}
public bool Create(CertBindingModel model)
{
CheckModel(model);
if (_certStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(CertBindingModel model)
{
CheckModel(model, false);
if (_certStorage.Delete(model) == null)
{
return false;
}
return true;
}
public CertViewModel? ReadElement(CertSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _certStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<CertViewModel>? ReadList(CertSearchModel? model)
{
var list = model == null ? _certStorage.GetFullList() : _certStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(CertBindingModel model)
{
CheckModel(model);
if (_certStorage.Update(model) == null)
{
return false;
}
return true;
}
private void CheckModel(CertBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия сертификата", nameof(model.Name));
}
if (string.IsNullOrEmpty(model.Path))
{
throw new ArgumentNullException("Нет пути сертификата", nameof(model.Path));
}
var element = _certStorage.GetElement(new CertSearchModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,102 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuisnessLogic.BuisnessLogic
{
public class KeyLogic : IKeyLogic
{
private readonly IKeyStorage _keyStorage;
public KeyLogic(IKeyStorage keyStorage)
{
_keyStorage = keyStorage;
}
public bool Create(KeyBindingModel model)
{
CheckModel(model);
if (_keyStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(KeyBindingModel model)
{
CheckModel(model, false);
if (_keyStorage.Delete(model) == null)
{
return false;
}
return true;
}
public KeyViewModel? ReadElement(KeySearchModel? model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _keyStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<KeyViewModel>? ReadList(KeySearchModel? model)
{
var list = model == null ? _keyStorage.GetFullList() : _keyStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(KeyBindingModel model)
{
CheckModel(model);
if (_keyStorage.Update(model) == null)
{
return false;
}
return true;
}
private void CheckModel(KeyBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет имени ключа", nameof(model.Name));
}
if (string.IsNullOrEmpty(model.Path))
{
throw new ArgumentNullException("Нет пути ключп", nameof(model.Name));
}
var element = _keyStorage.GetElement(new KeySearchModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Ключ с таким именем уже есть");
}
}
}
}

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace Contracts.BusinessLogicsContracts
{
public interface ISearchLogic
public interface ICertLogic
{
List<CertViewModel>? ReadList(CertSearchModel? model);
CertViewModel? ReadElement(CertSearchModel? model);