EL_Singature/Library/Engine.cs
2023-05-25 08:32:53 +04:00

150 lines
6.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using ElectronicSignature.Certification;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Security;
public class Engine
{
/// <summary>
/// Эта тестовая функция может генерировать пару открытых и закрытых ключей с использованием алгоритма шифрования RSA.
/// Это широко используемый алгоритм для генерации защищенных ключей, который часто используется для защищенной связи.
/// </summary>
public static void GenerateRSAKeyPair(string keyPairPath)
{
var keyPair = Cryptography.GenerateRSAKeyPair();
keyPair.ToPemFile(keyPairPath);
}
/// <summary>
/// Этой тестовой функцией может быть запись пары ключей в файл или создание закрытого и открытого ключей.
/// Закрытые ключи используются в асимметричном шифровании, где один ключ используется для шифрования, а другой - для дешифрования.
/// </summary>
public static void WriteKeyPairInPemFile(string keyPairPath, string privateKeyPath, string publicKeyPath)
{
var keyPair = keyPairPath.GetKeyPairFromPem();
keyPair.Private.ToPemFile(privateKeyPath);
keyPair.Public.ToPemFile(publicKeyPath);
}
/// <summary>
/// Эта тестовая функция может генерировать запрос на подпись сертификата (CSR), который представляет собой сообщение, отправляемое в центр сертификации для запроса цифрового сертификата.
/// </summary>
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);
csr.ToPemFile(csrPath);
}
/// <summary>
/// Эта тестовая функция может генерировать самозаверяющий сертификат.
/// Самозаверяющие сертификаты - это цифровые сертификаты, подписанные тем же лицом, которое выдает сертификат.
/// </summary>
public static void GenerateSelfSignedCert(string csrPath, string keyPairPath, string selfSignedCertPath)
{
var selfSignedCert = Cryptography.GenerateSelfSignedCert(csrPath.GetCSRPemFile(),
keyPairPath.GetPrivateKeyFromPem(),
DateTime.UtcNow,
DateTime.UtcNow.AddYears(1));
selfSignedCert.ToPemFile(selfSignedCertPath);
}
/// <summary>
/// Этой тестовой функцией может быть создание файла PFX, который представляет собой формат файла, используемый для безопасного хранения закрытых ключей и сертификатов.
/// </summary>
public static void CreatePfx(string keyPairPath, string selfSignedCertPath, string privateCertPath)
{
var certificate = new X509Certificate2(selfSignedCertPath);
var keyPair = keyPairPath.GetKeyPairFromPem();
var bcRsaPrivateKey = (RsaPrivateCrtKeyParameters)keyPair.Private;
var rsaParameters = DotNetUtilities.ToRSAParameters(bcRsaPrivateKey);
var rsaKey = RSA.Create(rsaParameters);
// Assuming you have an X509Certificate2 named certificate
var exportableCertificate = certificate.CopyWithPrivateKey(rsaKey);
// Create password for certificate protection
var passwordForCertificateProtection = new SecureString();
foreach (var @char in "1234")
passwordForCertificateProtection.AppendChar(@char);
// Export certificate to a file.
File.WriteAllBytes(privateCertPath, exportableCertificate.Export(X509ContentType.Pfx, passwordForCertificateProtection));
}
/// <summary>
/// Эта тестовая функция может генерировать подписанный сертификат.
/// Подписанный сертификат - это цифровой сертификат, который был подписан доверенной третьей стороной, известной как центр сертификации.
/// </summary>
public static void GenerateSignedCert(string csrPath, string privateCertPath, string privateCertPass, string signedCertPath)
{
var signedCert = Cryptography.GenerateSignedCertificate(csrPath.GetCSRPemFile(),
privateCertPath.GetPrivateCert(privateCertPass),
privateCertPath,
DateTime.UtcNow,
DateTime.UtcNow.AddYears(1));
signedCert.ToPemFile(signedCertPath);
}
/// <summary>
/// Эта тестовая функция может проверять, что сертификат был подписан закрытым ключом.
/// </summary>
public static bool VerifySignedByPrivateKey(string privateKeyPath, string publicKeyPath)
{
var message = "Hello world";
var signature = Cryptography.SignDataByPrivateKey(message, privateKeyPath.GetPrivateKeyFromPem());
if (Cryptography.VerifySignedByPublicKey(message, signature, publicKeyPath.GetPublicKeyFromPem()))
return true;
else
return false;
}
public static bool WriteKeyOnFile(string file_path, string file_for_save_path, string public_key_path)
{
FileStream? fstream = null;
try
{
fstream = File.OpenRead(file_path);
var encoded = Cryptography.EncryptDataByPublicCert(fstream.ToString(), public_key_path.GetPublicCert());
fstream?.Close();
fstream = new FileStream(file_for_save_path, FileMode.OpenOrCreate);
fstream?.Write(encoded);
fstream?.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// Функция может проверять, что сертификат был подписан закрытым ключом.
/// </summary>
public static bool CheckKeyinFIle(string file_path, string open_key_path, string private_key_path, string pass)
{
FileStream? fstream = null;
try
{
fstream = new FileStream(file_path, FileMode.Open);
var signature = Cryptography.SignDataByPrivateCert(fstream.ToString(), private_key_path.GetPrivateCert(pass));
fstream.Close();
if (!Cryptography.VerifySignedDataByCertIssuer(signature, open_key_path.GetPublicCert(), out var data))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
}