UKEP con TSP, OSCP y C # .NET Core 3.1

Construiré mi propio servicio de firma de documentos - FOX ©
Construiré mi propio servicio de firma de documentos - FOX ©

Introducción importante

La guía describe la formación de una firma separada en formato PKCS7 (aparecerá un archivo en formato .sig junto al archivo). Dicha firma puede ser solicitada por un notario, el Banco Central y cualquier persona que necesite un almacenamiento a largo plazo del documento firmado. La conveniencia de tal firma es que cuando se actualiza a CAdES-X Long Type 1 (CMS Advanced Electronic Signatures [1]), se le agrega un sello de tiempo que genera TSA (Time-Stamp Protocol [2]) y el estado del certificado en el momento Firmas (OCSP [3]): la autenticidad de dicha firma se puede verificar durante un período prolongado (Firma calificada mejorada [4]).





corefx DotnetCoreSampleProject - corefx. [5], .NET Core -. . Visual Studio Community 2019.





TSP- http://qs.cryptopro.ru/tsp/tsp.srf





?

  1. CSP 5.0 - (, )





  2. TSP Client 2.0 -





  3. OCSP Client 2.0 -





  4. .NET Client -





  5. - . .





  6. 34.11-2012/34.10-2012 256 bit,





  1. CSP 5.0 - 5.0.11944 1, .





  2. TSP Client 2.0 OCSP Client 2.0 - , .





  3. .NET Client 1.0.7132.2 - . .





  4. . , . , .





, ?

, .sig . :





  1. , PKCS#7 ;









    1. " " - ,





      Columna "Hora de creación del EP"
      " "
    2. ( ) " " :





      1. :





      2. :





    3. " ", " " " ". : , .





  2. . , , :





    Firma mejorada confirmada

34.11-2012 256 bit

. DotnetCoreSampleProject - .





... .





2 - , . .\runtime .\packages





I - corefx Windows

  1. 5.0 , . - ;





  2. core 3.1 sdk runtime Visual C++ Visual Studio 2015 ; .: II C++ - DIA SDK.





  3. DOTNET_MULTILEVEL_LOOKUP 0 - , ;





  4. 2 corefx (package_windows_debug.zip runtime-debug-windows.zip) - . v3.1.1-cprocsp-preview4.325 04.02.2021:





    1. package_windows_debug.zip .\packages





    2. runtime-debug-windows.zip .\runtime





  5. NuGet %appdata%\NuGet\NuGet.Config - .\packages . . , VS Community;





  6. NetStandard.Library .\ PowerShell ( ), $env:userprofile\.nuget\packages\





    git clone https://github.com/CryptoProLLC/NetStandard.Library
    New-Item -ItemType Directory -Force -Path "$env:userprofile\.nuget\packages\netstandard.library"
    Copy-Item -Force -Recurse ".\NetStandard.Library\nugetReady\netstandard.library" -Destination "$env:userprofile\.nuget\packages\"
          
          



  7. DotnetCoreSampleProject .\





  8.  .\DotnetSampleProject\DotnetSampleProject.csproj - System.Security.Cryptography.Pkcs.dll System.Security.Cryptography.Xml.dll .\runtime;





  9. . Visual Studio .





II - corefx Windows

  1. 1-3 6- I ;





  2. corefx .\





  3. .\corefx\build.cmd - DIA SDK





  4. 5, 7-9 I . .\packages .\corefx\artifacts\packages\Debug\NonShipping, .\runtime .\corefx\artifacts\bin\runtime\netcoreapp-Windows_NT-Debug-x64





, 34.11-2012 256 bit.





2 COM : "CAPICOM v2.1 Type Library" "Crypto-Pro CAdES 1.0 Type Library". .





BASE64 , PDF-. hash- .





PDF - Page 2 (cryptopro.ru) PDF c# (cryptopro.ru), PDF . .





4 :





  1. - ;





  2. ;





  3. ;





  4. .





using CAdESCOM;
using CAPICOM;
using System;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

public static void Main()
{
  //  
	X509Certificate2 gostCert = GetX509Certificate2("");
  //,   
  byte[] fileBytes = File.ReadAllBytes("C:\\ .pdf");
  //  
  byte[] signatureBytes = SignWithAdvancedEDS(fileBytes, gostCert);
  //  
  File.WriteAllBytes("C:\\Users\\mikel\\Desktop\\ .pdf.sig", signatureBytes);
}

//   
public static X509Certificate2 GetX509Certificate2(string thumbprint)
{
  X509Store store = CreateStoreObject("My", StoreLocation.CurrentUser);
  store.Open(OpenFlags.ReadOnly);

  X509Certificate2Collection certCollection =
    store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);

  X509Certificate2Enumerator enumerator = certCollection.GetEnumerator();
  X509Certificate2 gostCert = null;
  while (enumerator.MoveNext())
    gostCert = enumerator.Current;
  if (gostCert == null)
    throw new Exception("Certificiate was not found!");

  return gostCert;
}

// 
public static byte[] SignWithAdvancedEDS(byte[] fileBytes, X509Certificate2 certificate)
{
  string signature = "";
  
  try
  {
    string tspServerAddress = @"http://qs.cryptopro.ru/tsp/tsp.srf";

    CPSigner cps = new CPSigner();
    cps.Certificate = GetCAPICOMCertificate(certificate.Thumbprint);
    cps.Options = CAPICOM_CERTIFICATE_INCLUDE_OPTION.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN;
    cps.TSAAddress = tspServerAddress;

    CadesSignedData csd = new CadesSignedData();
    csd.ContentEncoding = CADESCOM_CONTENT_ENCODING_TYPE.CADESCOM_BASE64_TO_BINARY;
    csd.Content = Convert.ToBase64String(fileBytes);

    //    CAdES BES
    signature = csd.SignCades(cps, CADESCOM_CADES_TYPE.CADESCOM_CADES_BES, true, CAdESCOM.CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
    csd.VerifyCades(signature, CADESCOM_CADES_TYPE.CADESCOM_CADES_BES, true);
    
    //    CAdES BES   CAdES X Long Type 1 
    //(    ,     CAdES X Long Type 1)
    signature = csd.EnhanceCades(CADESCOM_CADES_TYPE.CADESCOM_CADES_X_LONG_TYPE_1, tspServerAddress, CAdESCOM.CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
    csd.VerifyCades(signature, CADESCOM_CADES_TYPE.CADESCOM_CADES_X_LONG_TYPE_1, true);
  }
  catch (Exception ex)
  {
    throw ex;
  }
  return Convert.FromBase64String(signature);
}
      
      



PDF-, " .":





No necesitamos nada más para la prueba.

:





. .





:





:





:





" ", " " " ":





, TSP- http://qs.cryptopro.ru/tsp/tsp.srf





.

Done.

- .NET Core 3.1 .





" " , .





?

.





[1] CMS Advanced Electronic Signatures (CAdES) - https://tools.ietf.org/html/rfc5126#ref-ISO7498-2





[2] Internet X.509 Public Key Infrastructure Time-Stamp Protocol (TSP) - https://www.ietf.org/rfc/rfc3161.txt





[3] X.509 Internet Public Key Infrastructure Online Certificate Status Protocol - OCSP - https://tools.ietf.org/html/rfc2560





[4] — (kontur.ru)





[5] .NET Core (cryptopro.ru)





[6] http://qs.cryptopro.ru/tsp/tsp.srf - Servicio TSP de CryptoPro





UPD1: Se modificó la variable en el código donde se escriben los bytes del archivo de firma.





También olvidé escribir un poco sobre la firma del sello de tiempo: está firmada por el certificado del propietario del servicio TSP. Según la guía, esto es CRYPTO-PRO LLC:








All Articles