here in Italy, we will need to digitally sign all invoices since January 2019.
I found a code that works well with sha-1, but I need to use sha256 as standard. The code below, after successfully detect USB key, and ask me for the certificate to use try to sign "NomeFile" file After and output in "NomeFile".p7m, when the line
signedCms.ComputeSignature(signer,false);
runs, it happens: 1- if use sha-1 it asks me for the PIN and document is successfully created. 2- if use sha-256 don't ask for PIN and gives me Unknown error -1073741275
I read a lot of posts that are all old (2011-2014). Other people have the same problem and seem that Microsoft has some bug using sha256.
Now we are at end of 2018 and I tried this code in .net 4, 4.6.1 and 4.7.2 but the error is the same.
Somebody can tell me if Microsoft corrects the problem with sha256 and what could be this strange error? (-1073741275) Error Stack
public String FirmaFile(String NomeFile, DateTime DataFirma, X509Certificate2 cert, out string RisFirma)
{
String NomeFirma = NomeFile + ".p7m";
RisFirma = "";
try
{
// content contiene il file da firmare
ContentInfo content = new ContentInfo((File.ReadAllBytes(NomeFile)));
// assegniamo content ad un oggetto di tipo SignedCms
SignedCms signedCms = new SignedCms(SubjectIdentifierType.IssuerAndSerialNumber, content, false);
// si instanzia un oggetto CmsSigner che espone i metodi di firma.
CmsSigner signer = new CmsSigner(cert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
//signer.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1");
signer.DigestAlgorithm = new Oid("SHA256");
signer.SignedAttributes.Add(new Pkcs9SigningTime(DataFirma));
try
{
// Viene calcolata la firma del file (in formato PKCS7)
signedCms.ComputeSignature(signer,false);
}
catch (CryptographicException CEx)
{
RisFirma = "Errore: " + CEx.Message + " Stack: " + CEx.StackTrace;
return RisFirma;
}
// si pone il file firmato in un array.
byte[] signature = signedCms.Encode();
File.WriteAllBytes(NomeFirma, signature);
RisFirma = "true";
}
catch (Exception Ex)
{
RisFirma = "Errore in FirmaFile: " + Ex.Message + " Stack: " + Ex.StackTrace;
}
return RisFirma;
}
NB: I tried 2 version of OID signer.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1"); signer.DigestAlgorithm = new Oid("SHA256");
All 2 give the same error.
I USE an INFOCERT USB KEY with driver bit4id (https://www.bit4id.com/it/4identity/) that is contained in USB Drive.