public static void ReadXmlSigned(this FatturaBase fattura, Stream stream, bool validateSignature = true)
        {
            CmsSignedData signedFile = new CmsSignedData(stream);

            if (validateSignature)
            {
                IX509Store             certStore   = signedFile.GetCertificates("Collection");
                ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
                SignerInformationStore signerStore = signedFile.GetSignerInfos();
                ICollection            signers     = signerStore.GetSigners();

                foreach (object tempCertification in certs)
                {
                    Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate;

                    foreach (object tempSigner in signers)
                    {
                        SignerInformation signer = tempSigner as SignerInformation;
                        if (!signer.Verify(certification.GetPublicKey()))
                        {
                            throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException);
                        }
                    }
                }
            }

            using (var memoryStream = new MemoryStream())
            {
                signedFile.SignedContent.Write(memoryStream);
                fattura.ReadXml(memoryStream);
            }
        }
Exemple #2
0
        private void SerializeAndAssertRootElementAttributes(FatturaBase f)
        {
            using (var w = XmlWriter.Create("test", new XmlWriterSettings {
                Indent = true
            }))
            {
                f.WriteXml(w);
            }

            using (var r = XmlReader.Create("test"))
            {
                while (r.Read())
                {
                    if (r.NodeType == XmlNodeType.Element)
                    {
                        if (r.Prefix == RootElement.Prefix && r.LocalName == "FatturaElettronicaSemplificata")
                        {
                            Assert.AreEqual(((FatturaSemplificata)f).FatturaElettronicaHeader.DatiTrasmissione.FormatoTrasmissione, r.GetAttribute("versione"));
                            Assert.AreEqual("http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.0", r.NamespaceURI);
                            foreach (var a in RootElement.ExtraAttributes)
                            {
                                Assert.AreEqual(a.value, r.GetAttribute(string.Format("{0}:{1}", a.Prefix, a.LocalName)));
                            }
                            break;
                        }
                    }
                }
            }
            File.Delete("test");
        }
        public static void WriteXmlSigned(this FatturaBase fattura, X509Certificate2 cert, string p7mFilePath)
        {
            string res      = string.Empty;
            string tempFile = Path.GetTempFileName();

            if (!p7mFilePath.ToLowerInvariant().EndsWith(".p7m"))
            {
                p7mFilePath += ".p7m";
            }

            try
            {
                fattura.WriteXml(tempFile);

                ContentInfo content   = new ContentInfo(new Oid("1.2.840.113549.1.7.1", "PKCS 7 Data"), File.ReadAllBytes(tempFile));
                SignedCms   signedCms = new SignedCms(SubjectIdentifierType.IssuerAndSerialNumber, content, false);
                CmsSigner   signer    = new CmsSigner(cert);
                signer.IncludeOption   = X509IncludeOption.EndCertOnly;
                signer.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1", "SHA256");
                signer.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));
                try
                {
                    //PKCS7 format
                    signedCms.ComputeSignature(signer, false);
                }
                catch (CryptographicException cex)
                {
                    //To evaluate for the future https://stackoverflow.com/a/52897100

                    /*
                     * // Try re-importing the private key into a better CSP:
                     * using (RSA tmpRsa = RSA.Create())
                     * {
                     *  tmpRsa.ImportParameters(cert.GetRSAPrivateKey().ExportParameters(true));
                     *
                     *  using (X509Certificate2 tmpCertNoKey = new X509Certificate2(cert.RawData))
                     *  using (X509Certificate2 tmpCert = tmpCertNoKey.CopyWithPrivateKey(tmpRsa))
                     *  {
                     *      signer.Certificate = tmpCert;
                     *      signedCms.ComputeSignature(signer, false);
                     *  }
                     * }*/

                    throw cex;
                }
                byte[] signature = signedCms.Encode();
                File.WriteAllBytes(p7mFilePath, signature);
            }
            catch (Exception)
            {
                throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.FirmaException);
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Exemple #4
0
 public static void ReadXmlSigned(this FatturaBase fattura, Stream stream, bool validateSignature = true)
 {
     using (var parsed = ParseSignature(stream, validateSignature))
     {
         fattura.ReadXml(parsed);
     }
 }
 private FatturaBase DeserializeAny(string fileName)
 {
     using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
     {
         return(FatturaBase.CreateInstanceFromXml(fileStream));
     }
 }
Exemple #6
0
        public static void WriteHtml(this FatturaBase fattura, string outPath, string xslPath)
        {
            if (outPath == null)
            {
                throw new ArgumentNullException(nameof(outPath));
            }

            if (xslPath == null)
            {
                throw new ArgumentNullException(nameof(xslPath));
            }

            var tempXml = Path.GetTempFileName();

            using (var w = XmlWriter.Create(tempXml, new XmlWriterSettings {
                Indent = true
            }))
            {
                fattura.WriteXml(w);
            }

            var xt = new XslCompiledTransform();

            xt.Load(xslPath);
            xt.Transform(tempXml, outPath);
        }
 public void CreatePrivatiInstance()
 {
     _challenge = FatturaOrdinaria.CreateInstance(Instance.Privati);
     Assert.AreEqual(FormatoTrasmissione.Privati,
                     ((FatturaOrdinaria)_challenge).FatturaElettronicaHeader.DatiTrasmissione.FormatoTrasmissione);
     Assert.AreEqual("0000000",
                     ((FatturaOrdinaria)_challenge).FatturaElettronicaHeader.DatiTrasmissione.CodiceDestinatario);
 }
 public static void ReadXml(this FatturaBase fattura, string filePath)
 {
     using (var r = XmlReader.Create(filePath, new XmlReaderSettings {
         IgnoreWhitespace = true, IgnoreComments = true, IgnoreProcessingInstructions = true
     }))
     {
         fattura.ReadXml(r);
     }
 }
 public static void WriteXml(this FatturaBase fattura, string filePath)
 {
     using (var w = XmlWriter.Create(filePath, new XmlWriterSettings {
         Indent = true
     }))
     {
         fattura.WriteXml(w);
     }
 }
 public static void ReadXml(this FatturaBase fattura, Stream stream)
 {
     stream.Position = 0;
     using (var r = XmlReader.Create(stream, new XmlReaderSettings {
         IgnoreWhitespace = true, IgnoreComments = true, IgnoreProcessingInstructions = true
     }))
     {
         fattura.ReadXml(r);
     }
 }
        public static void WriteXmlSigned(this FatturaBase fattura, string pfxFile, string pfxPassword, string p7mFilePath)
        {
            if (!File.Exists(pfxFile))
            {
                throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.PfxIsMissing);
            }

            var cert = new X509Certificate2(pfxFile, pfxPassword);

            WriteXmlSigned(fattura, cert, p7mFilePath);
        }
 public static void ReadXmlSigned(this FatturaBase fattura, string filePath, bool validateSignature = true)
 {
     try
     {
         // Most times input will be a plain (non-Base64-encoded) file.
         using var inputStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
         ReadXmlSigned(fattura, inputStream, validateSignature);
     }
     catch (CmsException)
     {
         ReadXmlSignedBase64(fattura, filePath, validateSignature);
     }
 }
        private void SerializeAndAssertRootElementAttributes(FatturaBase f)
        {
            using (var w = XmlWriter.Create("test", new XmlWriterSettings {
                Indent = true
            }))
            {
                f.WriteXml(w);
            }

            using (var r = XmlReader.Create("test"))
            {
                while (r.Read())
                {
                    if (r.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }
                    if (r.Prefix != RootElement.Prefix || r.LocalName != "FatturaElettronica")
                    {
                        continue;
                    }

                    Assert.AreEqual(
                        ((FatturaOrdinaria)f).FatturaElettronicaHeader.DatiTrasmissione.FormatoTrasmissione,
                        r.GetAttribute("versione"));
                    Assert.AreEqual(f.SistemaEmittente, r.GetAttribute("SistemaEmittente"));
                    Assert.AreEqual("http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2", r.NamespaceURI);
                    foreach (var a in RootElement.ExtraAttributes)
                    {
                        Assert.AreEqual(a.value, r.GetAttribute($"{a.Prefix}:{a.LocalName}"));
                    }

                    break;
                }
            }

            File.Delete("test");
        }
        public static void WriteHtml(this FatturaBase fattura, string outPath, string xslPath)
        {
            if (outPath == null)
            {
                throw new ArgumentNullException(nameof(outPath));
            }

            if (xslPath == null)
            {
                throw new ArgumentNullException(nameof(xslPath));
            }

            var xt = new XslCompiledTransform();

            xt.Load(xslPath);

            using (var memoryStream = new MemoryStream())
            {
                using (var w = new XmlTextWriter(memoryStream, Encoding.UTF8)
                {
                    Formatting = Formatting.Indented
                })
                {
                    fattura.WriteXml(w);
                    w.Flush();

                    memoryStream.Seek(0, SeekOrigin.Begin);

                    var xPathDocument = new XPathDocument(memoryStream);
                    using (var writer = File.OpenWrite(outPath))
                    {
                        xt.Transform(xPathDocument, null, writer);
                    }
                }
            }
        }
 public void CreatePubblicaAmministrazioneInstance()
 {
     challenge = FatturaOrdinaria.CreateInstance(Instance.PubblicaAmministrazione);
     Assert.AreEqual(FormatoTrasmissione.PubblicaAmministrazione, ((FatturaOrdinaria)challenge).FatturaElettronicaHeader.DatiTrasmissione.FormatoTrasmissione);
 }
Exemple #16
0
 public static void FromJson(this FatturaBase fattura, string json)
 {
     fattura.FromJson(new Utf8JsonReader(Encoding.UTF8.GetBytes(json)));
 }
Exemple #17
0
        public List <ReadInvoiceResult> ReadInvoices()
        {
            List <ReadInvoiceResult> readingResult = new List <ReadInvoiceResult>();

            var readerSettings = new XmlReaderSettings
            {
                IgnoreWhitespace             = true,
                IgnoreComments               = true,
                IgnoreProcessingInstructions = true
            };

            List <string> files = Directory.GetFiles(InvoicePath).ToList();

            foreach (var file in files)
            {
                var readInvoiceResult = new ReadInvoiceResult();

                if (Path.GetExtension(file) != ".xml")
                {
                    readInvoiceResult.FileIsValid = false;

                    continue;
                }

                using var stream = new FileStream(file, FileMode.Open, FileAccess.Read);

                FatturaBase tempInvoice = null;

                try
                {
                    tempInvoice = FatturaBase.CreateInstanceFromXml(stream);
                } catch
                {
                    readInvoiceResult.InvoiceIsValid   = false;
                    readInvoiceResult.FileIsValid      = false;
                    readInvoiceResult.IsForOwner       = false;
                    readInvoiceResult.ValidationResult = null;

                    readInvoiceResult.FileName = Path.GetFileName(file);

                    readingResult.Add(readInvoiceResult);
                    continue;
                }

                if (tempInvoice.GetType() == typeof(FatturaOrdinaria))
                {
                    readInvoiceResult.Ordinaria        = new FatturaOrdinaria();
                    readInvoiceResult.Ordinaria        = (FatturaOrdinaria)tempInvoice;
                    readInvoiceResult.ValidationResult = readInvoiceResult.Ordinaria.Validate();
                }
                else
                {
                    readInvoiceResult.Semplificata     = new FatturaSemplificata();
                    readInvoiceResult.Semplificata     = (FatturaSemplificata)tempInvoice;
                    readInvoiceResult.ValidationResult = readInvoiceResult.Semplificata.Validate();
                }


                readInvoiceResult.InvoiceIsValid = readInvoiceResult.ValidationResult.IsValid;

                IdFiscaleIVA IdFiscaleSupplier = new IdFiscaleIVA();
                IdFiscaleIVA IdFiscaleClient   = new IdFiscaleIVA();

                if (readInvoiceResult.Ordinaria != null)
                {
                    IdFiscaleSupplier = ((FatturaOrdinaria)readInvoiceResult.Ordinaria).FatturaElettronicaHeader.CedentePrestatore.DatiAnagrafici.IdFiscaleIVA;
                    IdFiscaleClient   = ((FatturaOrdinaria)readInvoiceResult.Ordinaria).FatturaElettronicaHeader.CessionarioCommittente.DatiAnagrafici.IdFiscaleIVA;
                }
                else
                {
                    IdFiscaleSupplier = ((FatturaSemplificata)readInvoiceResult.Semplificata).FatturaElettronicaHeader.CedentePrestatore.IdFiscaleIVA;
                    IdFiscaleClient   = ((FatturaSemplificata)readInvoiceResult.Semplificata).FatturaElettronicaHeader.CessionarioCommittente.IdentificativiFiscali.IdFiscaleIVA;
                }

                readInvoiceResult.IsForOwner = EitherIsOwner(IdFiscaleSupplier, IdFiscaleClient);

                readInvoiceResult.FileName = Path.GetFileName(file);

                readingResult.Add(readInvoiceResult);
            }

            return(readingResult);
        }
 public static void ReadXmlSignedBase64(this FatturaBase fattura, string filePath, bool validateSignature = true)
 {
     ReadXmlSigned(fattura, new MemoryStream(Convert.FromBase64String(File.ReadAllText(filePath))), validateSignature);
 }
Exemple #19
0
 public static void FromJson(this FatturaBase fattura, string json)
 {
     fattura.FromJson(new JsonTextReader(new StringReader(json)));
 }
 public static void WriteXml(this FatturaBase fattura, string filePath)
 {
     using var w = XmlWriter.Create(filePath, new() { Indent = true });
     fattura.WriteXml(w);
 }
Exemple #21
0
 public static void WriteXml(this FatturaBase fattura, string filePath)
 {
     using var w = XmlWriter.Create(new StringBuilder(filePath), new XmlWriterSettings { Indent = true });
     fattura.WriteXml(w);
 }