Imaginsystems


Tecniche di Programmazione - Codici Sorgenti - News Informatiche
Archivio Posts
Anno 2014

Anno 2013

Anno 2012
Statistiche
  • Views Home Page: 71.612
  • Views Posts: 542.487
  • Views Gallerie: 0
  • n° Posts: 210
  • n° Commenti: 224

C# - Firmare documenti digitalmente con BouncyCastle in standard CAdES sha256

C# - Firmare documenti digitalmente con BouncyCastle in standard CAdES sha256


 

Oggi vediamo come firmare digitalmente documenti elettronici con i nuovi standard CAdES a cifratura sha256 utilizzando le librerie gratuite BouncyCastle con qualche opportuna modifica.

Cominciamo con aprire visual studio e un nuovo progetto C# di tipo form form application.Recuperiamo da internet le librerie BouncyCastle recuperabili al seguente indirizzo: http://www.bouncycastle.org/csharp/ . Link Mirror File Download Fatto questo apriamo il nostro form generato automaticamente e cominciamo a programmare per prima cosa importando nelle reference le librerie appena scaricate

Riportati sotto i riferimenti:

 

Allego la libreria crypto aggiunta della classe CmsSignedDataGenWithRsaCsp() la potete scaricare al seguente link : Download crypto.zip 
Se volete capire come è formata la funzione CmsSignedDataGenWithRsaCsp() la potete scaricare al seguente link : Download  CmsSignedDataGenWithRsaCsp

CODICE VISUAL STUDIO 2013 - C#

 using Microsoft.VisualBasic;

using System;

using System.Collections;

using System.Collections.Generic;

using System.Data;

using System.Diagnostics;

using System.Security.Cryptography;

using Org.BouncyCastle.Asn1.Ess;

using Org.BouncyCastle.Asn1;

using CryptoUpgNet.NonExportablePK;

using Org.BouncyCastle.Security;

using System.IO;

using Org.BouncyCastle.Cms;

using System.Security.Cryptography.X509Certificates;

using System.Security.Permissions;

using System.Text;

using System.Windows.Forms;


Dopo che abbiamo importato la libreria passiamo ad aggiungere un bottone nella nostra schermata/form che ci servirà per selezionare il file da firmare oltre che alla selezione del certificato da utilizzare. 

CODICE VISUAL STUDIO 2013 - C#

 private void SignFile_Click(object sender, EventArgs e)

        {

            try

            {

                //mi seleziono il certificato da utilizzare per Firmare il File selezionato

                X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);

                st.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection col = st.Certificates;

                X509Certificate2 card = null;


                X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection);


                if (sel.Count > 0)

                {

                    X509Certificate2Enumerator en = sel.GetEnumerator();

                    en.MoveNext();

                    card = en.Current;

                }

                st.Close();


                if (card != null)

                {

                    openFileDialog1.ShowDialog();

                    if (!string.IsNullOrEmpty(openFileDialog1.FileName))

                    {

                        string Res = "";

                        string NomeFile = openFileDialog1.FileName;

                        byte[] Firmato = FirmaFileBouncy(NomeFile, card, ref Res);

                        if (string.IsNullOrEmpty(Res))

                        {

                            File.WriteAllBytes(NomeFile + ".p7m", Firmato);

                            MessageBox.Show("Messaggio Firmato Con Successo");

                        }

                        else

                        {

                            throw new Exception(Res);

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

        }


Passiamo a scrivere anche il metodo della classe FirmaFileBouncy(..) che viene richiamata dal codice precedente.

CODICE VISUAL STUDIO 2013 - C#

       public byte[] FirmaFileBouncy(String NomeFile, X509Certificate2 cert, ref string RisFirma)

        {

            try

            {

                SHA256Managed hashSha256 = new SHA256Managed();

                byte[] certHash = hashSha256.ComputeHash(cert.RawData);

                

                EssCertIDv2 essCert1 = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);

                SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });

               

                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2,new DerSet(scv2));

                Asn1EncodableVector v = new Asn1EncodableVector();

                v.Add(CertHAttribute);


                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);

                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();

                

                Org.BouncyCastle.Crypto.AsymmetricKeyParameter keyParameter = null;

             

                dynamic rsa = (RSACryptoServiceProvider)cert.PrivateKey;

                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert);

                cms.MyAddSigner(rsa, certCopy, keyParameter, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);

                ArrayList certList = new ArrayList();

                certList.Add(certCopy);

                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP =

                new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);

                Org.BouncyCastle.X509.Store.IX509Store st1 =

                Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

                cms.AddCertificates(st1);


                //mi ricavo il file da firmare

                FileInfo File__1 = new FileInfo(NomeFile);

                CmsProcessableFile file__2 = new CmsProcessableFile(File__1);

                CmsSignedData Firmato = cms.Generate(file__2, true);

                byte[] Encoded = Firmato.GetEncoded();

                RisFirma = "";

                return Encoded;

            }

            catch (Exception ex)

            {

                RisFirma = ex.ToString();

                return null;

            }

        }


Ora il gioco è fatto e pronto a funzionare.. Vi allego anche il file zip contenente tutto il necessario per iniziare a fare le vostre prove..
Link Download File Source :  In fase di caricamento.

By ImaginSystems & Queen Gin   
Categoria: C#
lunedì, 26 mag 2014 Ore. 18.29

Messaggi collegati


Ora e Data
Mappa
Blogs Amici
    Copyright © 2002-2007 - Blogs 2.0
    dotNetHell.it | Home Page Blogs
    ASP.NET 2.0 Windows 2003