private byte[] GenerateTSRFile(byte[] originalContent, string fileName, byte[] timestampResponse) { DerIA5String derIA5String = null; if (!string.IsNullOrEmpty(fileName)) { derIA5String = new DerIA5String(fileName); } BerOctetString berOctetStrings = new BerOctetString(originalContent); TimeStampResponse timeStampResponse = new TimeStampResponse(timestampResponse); TimeStampAndCrl timeStampAndCrl = new TimeStampAndCrl(timeStampResponse.TimeStampToken.ToCmsSignedData().ContentInfo); Evidence evidence = new Evidence(new TimeStampTokenEvidence(timeStampAndCrl)); TimeStampedData timeStampedDatum = new TimeStampedData(derIA5String, null, berOctetStrings, evidence); return((new ContentInfo(CmsObjectIdentifiers.timestampedData, timeStampedDatum)).GetEncoded()); }
public CryptoFile create(CryptoFile p7mFile, CryptoFile[] tsrFiles) { List <TimeStampAndCrl> tsCRLLst = new List <TimeStampAndCrl>(); Asn1OctetString p7mOctecString = (Asn1OctetString) new DerOctetString(p7mFile.Content).ToAsn1Object(); foreach (CryptoFile tsrFile in tsrFiles) { TimeStampResponse tsr = new TimeStampResponse(tsrFile.Content); TimeStampAndCrl tsCRL = new TimeStampAndCrl(tsr.TimeStampToken.ToCmsSignedData().ContentInfo); tsCRLLst.Add(tsCRL); } Evidence ev = new Evidence(new TimeStampTokenEvidence(tsCRLLst.ToArray())); TimeStampedData newTSD = new TimeStampedData(null, null, p7mOctecString, ev); ContentInfo info = new ContentInfo(CmsObjectIdentifiers.timestampedData, newTSD.ToAsn1Object()); CryptoFile retval = new CryptoFile { Content = info.GetDerEncoded(), Name = "default.tsd", MessageFileType = fileType.Binary }; return(retval); }
public void explode(byte[] fileContents) { try { Asn1Sequence sequenza = Asn1Sequence.GetInstance(fileContents); DerObjectIdentifier tsdOIDFile = sequenza[0] as DerObjectIdentifier; if (tsdOIDFile != null) { if (tsdOIDFile.Id == CmsObjectIdentifiers.timestampedData.Id) //TSD { DerTaggedObject taggedObject = sequenza[1] as DerTaggedObject; if (taggedObject != null) { Asn1Sequence asn1seq = Asn1Sequence.GetInstance(taggedObject, true); TimeStampedData tsd = TimeStampedData.GetInstance(asn1seq); _p7m = new CryptoFile { Content = tsd.Content.GetOctets(), MessageFileType = fileType.Binary, Name = "default.p7m" }; TimeStampAndCrl[] crlTS = tsd.TemporalEvidence.TstEvidence.ToTimeStampAndCrlArray(); foreach (TimeStampAndCrl tokCRL in crlTS) { TimeStampToken tsToken = new TimeStampToken(tokCRL.TimeStampToken); ContentInfo o = tokCRL.TimeStampToken; Org.BouncyCastle.Asn1.Cmp.PkiStatusInfo si = new Org.BouncyCastle.Asn1.Cmp.PkiStatusInfo(0); Org.BouncyCastle.Asn1.Tsp.TimeStampResp re = new Org.BouncyCastle.Asn1.Tsp.TimeStampResp(si, o); string serial = tsToken.TimeStampInfo.SerialNumber.ToString(); _tsr.Add(new CryptoFile { Content = re.GetEncoded(), Name = String.Format("default.{0}.tsr", serial), MessageFileType = fileType.Binary }); } } } } } catch (Exception e) { throw e; } }
/// <summary> /// Verifiy of CRL /// </summary> /// <param name="fileContents">byte Array file contents</param> /// <param name="endPoint">not used </param> /// <param name="args">1) Datetime? data verifica / string cachePath / string (bool) nocache</param> /// <returns></returns> public EsitoVerifica VerificaByteEV(byte[] fileContents, string endPoint, Object[] args) { //string ID = String.Format("{0}-{1}", Environment.GetEnvironmentVariable("APP_POOL_ID").Replace(" ", ""), AppDomain.CurrentDomain.BaseDirectory); bool forceDownload = false; //end point lo usiamo per forzare il download string p7mSignAlgorithm = null; //string p7mSignHash = null; DocsPaVO.documento.Internal.SignerInfo[] certSignersInfo; EsitoVerifica ev = new EsitoVerifica(); DateTime?dataverificaDT = null; string cachePath = string.Empty; if (args == null) { logger.Debug("Args (Date) is null, settign current"); dataverificaDT = DateTime.Now; } if (args.Length > 0) { dataverificaDT = args[0] as DateTime?; if (dataverificaDT == null) { logger.Debug("Date is null, settign current"); dataverificaDT = DateTime.Now; } cachePath = args[1] as string; string fdl = args[2] as string; if (!String.IsNullOrEmpty(fdl)) { Boolean.TryParse(endPoint, out forceDownload); } } int posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("Mime-Version:")); if (posi == 0) //E' un mime m7m { using (MemoryStream ms = new MemoryStream(fileContents)) { anmar.SharpMimeTools.SharpMessage sm = new anmar.SharpMimeTools.SharpMessage(ms); if (sm.Attachments.Count > 0) { foreach (anmar.SharpMimeTools.SharpAttachment att in sm.Attachments) { if (System.IO.Path.GetExtension(att.Name).ToLower().Contains("p7m")) { att.Stream.Position = 0; BinaryReader sr = new BinaryReader(att.Stream); fileContents = sr.ReadBytes((int)att.Size); } } } } } // Ce provo.... posi = -1; posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("%PDF")); if (posi == 0) //E' un pdf { PdfReader pdfReader = isPdf(fileContents); try { AcroFields af = pdfReader.AcroFields; List <string> signNames = af.GetSignatureNames(); if (signNames.Count == 0) //Firma non è presente { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Il file PDF da verificare non contiene nessuna firma"; ev.errorCode = "1458"; return(ev); } List <DocsPaVO.documento.Internal.SignerInfo> siList = new List <DocsPaVO.documento.Internal.SignerInfo>(); foreach (string name in signNames) { PdfPKCS7 pk = af.VerifySignature(name); p7mSignAlgorithm = pk.GetHashAlgorithm(); Org.BouncyCastle.X509.X509Certificate[] certs = pk.Certificates; foreach (X509Certificate cert in certs) { DocsPaVO.documento.Internal.SignerInfo si = GetCertSignersInfo(cert); VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert, p7mSignAlgorithm); si = ControlloCRL(forceDownload, ev, cachePath, cert, si); siList.Add(si); } bool result = pk.Verify(); if (!result) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "La verifica della firma è fallita (File is Tampered)"; ev.errorCode = "1450"; } } /* * if ( * (pdfReader.PdfVersion.ToString() != "4")|| * (pdfReader.PdfVersion.ToString() != "7")) * { * ev.status = EsitoVerificaStatus.ErroreGenerico; * ev.message = "Il file da verificare non è conforme allo standard PDF 1.4 o pdf 1.7"; * ev.errorCode = "1457"; * } */ List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>(); DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document { SignersInfo = siList.ToArray(), DocumentFileName = null, Level = 0 }; p7docsLst.Add(p7doc); ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray()); ev.content = fileContents; } catch (Exception e) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Error verifying pdf message :" + e.Message; ev.errorCode = "1402"; return(ev); } } else //PKCS7 { try { int doclevel = 0; List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>(); do { //questa Estrazione serve solo per capire se uscire dal ciclo ricorsivo e ritornare il content try { ev.content = extractSignedContent(fileContents); } catch { break; } //Ciclo per file firmato Asn1Sequence sequenza = Asn1Sequence.GetInstance(fileContents); DerObjectIdentifier tsdOIDFile = sequenza[0] as DerObjectIdentifier; if (tsdOIDFile != null) { if (tsdOIDFile.Id == CmsObjectIdentifiers.timestampedData.Id) //TSD { logger.Debug("Found TSD file"); DerTaggedObject taggedObject = sequenza[1] as DerTaggedObject; if (taggedObject != null) { Asn1Sequence asn1seq = Asn1Sequence.GetInstance(taggedObject, true); TimeStampedData tsd = TimeStampedData.GetInstance(asn1seq); fileContents = tsd.Content.GetOctets(); } } if (tsdOIDFile.Id == CmsObjectIdentifiers.SignedData.Id) //p7m { logger.Debug("Found P7M file"); } } CmsSignedData cms = new CmsSignedData(fileContents); //controllaCrlFileP7m(cms); IX509Store store = cms.GetCertificates("Collection"); SignerInformationStore signers = cms.GetSignerInfos(); SignedData da = SignedData.GetInstance(cms.ContentInfo.Content.ToAsn1Object()); Asn1Sequence DigAlgAsn1 = null; if (da.DigestAlgorithms.Count > 0) { DigAlgAsn1 = da.DigestAlgorithms[0].ToAsn1Object() as Asn1Sequence; } if (DigAlgAsn1 != null) { p7mSignAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID); } certSignersInfo = new DocsPaVO.documento.Internal.SignerInfo[signers.GetSigners().Count]; int i = 0; foreach (SignerInformation signer in signers.GetSigners()) { bool fileOK = false; Org.BouncyCastle.X509.X509Certificate cert1 = GetCertificate(signer, store); certSignersInfo[i] = GetCertSignersInfo(cert1); VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert1, p7mSignAlgorithm); fileOK = VerificaNonRepudiation(ev, fileOK, cert1); if (!fileOK) { certSignersInfo[i].CertificateInfo.messages = ev.errorCode + " " + ev.message; } try { fileOK = VerificaCertificato(ev, signer, fileOK, cert1); } catch (Exception e) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Error verifying 2, message :" + e.Message; ev.errorCode = "1450"; } if (fileOK) { certSignersInfo[i] = ControlloCRL(forceDownload, ev, cachePath, cert1, certSignersInfo[i]); } //p7mSignHash = BitConverter.ToString(Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID), (byte[])cms.SignedContent.GetContent())).Replace("-", ""); } /* * if (cms.SignedContent != null) * { * //CmsProcessable signedContent = cms.SignedContent; * //ev.content = (byte[])signedContent.GetContent(); * * ev.content = extractMatrioskaFile(fileContents); * * * * } */ DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document { SignersInfo = certSignersInfo, DocumentFileName = null, Level = doclevel++ }; p7docsLst.Add(p7doc); try { fileContents = extractSignedContent(fileContents); } catch { break; } } while (true); ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray());; } catch (Exception e) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Error verifying 1, message :" + e.Message; ev.errorCode = "1402"; return(ev); } } return(ev); }