예제 #1
0
        private void VerifySignatures(CmsSignedData s, byte[] contentDigest)
        {
            IX509Store             x509Certs = s.GetCertificates("Collection");
            IX509Store             x509Crls  = s.GetCrls("Collection");
            SignerInformationStore signers   = s.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                VerifySigner(signer, cert);

                if (contentDigest != null)
                {
                    Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
                }
            }

            ICollection certColl = x509Certs.GetMatches(null);
            ICollection crlColl  = x509Crls.GetMatches(null);

            Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count);
            Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count);
        }
예제 #2
0
        public static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream)
        {
            CmsProcessable signedContent = null;
            CmsSignedData  cmsSignedData = null;

            Org.BouncyCastle.X509.Store.IX509Store store = null;
            ICollection signers        = null;
            bool        verifiedStatus = false;

            try
            {
                //Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider());
                signedContent = new CmsProcessableFile(contentFile);
                cmsSignedData = new CmsSignedData(signedContent, signedDataStream);
                store         = cmsSignedData.GetCertificates("Collection");//.getCertificates();
                IX509Store certStore = cmsSignedData.GetCertificates("Collection");
                signers = cmsSignedData.GetSignerInfos().GetSigners();
                foreach (var item in signers)
                {
                    SignerInformation signer   = (SignerInformation)item;
                    var         certCollection = certStore.GetMatches(signer.SignerID);
                    IEnumerator iter           = certCollection.GetEnumerator();
                    iter.MoveNext();
                    var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current;
                    verifiedStatus = signer.Verify(cert.GetPublicKey());
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(verifiedStatus);
        }
예제 #3
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> list = new AList <X509Certificate>();

            try
            {
                if (!onlyExtended)
                {
                    LOG.Info(cmsSignedData.GetCertificates("Collection").GetMatches(null).Count + " certificate in collection"
                             );
                    //foreach (X509CertificateHolder ch in (ICollection<X509CertificateHolder>)cmsSignedData
                    foreach (X509Certificate ch in cmsSignedData
                             .GetCertificates("Collection").GetMatches(null))
                    {
                        //X509Certificate c = new X509CertificateObject(ch.ToASN1Structure());
                        X509Certificate c = ch;
                        LOG.Info("Certificate for subject " + c.SubjectDN);
                        if (!list.Contains(c))
                        {
                            list.AddItem(c);
                        }
                    }
                }
                // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
                SignerInformation si = cmsSignedData.GetSignerInfos().GetFirstSigner(signerId);
                if (si != null && si.UnsignedAttributes != null && si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues] != null)
                {
                    DerSequence seq = (DerSequence)si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues].AttrValues[0];
                    for (int i = 0; i < seq.Count; i++)
                    {
                        X509CertificateStructure cs = X509CertificateStructure.GetInstance(seq[i]);
                        //X509Certificate c = new X509CertificateObject(cs);
                        X509Certificate c = new X509Certificate(cs);
                        if (!list.Contains(c))
                        {
                            list.AddItem(c);
                        }
                    }
                }
            }
            catch (CertificateParsingException e)
            {
                throw new RuntimeException(e);
            }

            /*catch (StoreException e)
             * {
             *      throw new RuntimeException(e);
             * }*/
            return(list);
        }
예제 #4
0
        public static MemoryStream ParseSignature(Stream stream, bool validateSignature)
        {
            var signedFile = new CmsSignedData(stream);

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

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

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

            var memoryStream = new MemoryStream();

            signedFile.SignedContent.Write(memoryStream);
            return(memoryStream);
        }
예제 #5
0
 public SignatureDocument(CmsSignedData signedData)
 {
     _signedData         = signedData;
     _certs              = CmsUtilities.GetCertificatesFromStore(_signedData.GetCertificates("Collection"));
     _signaturePackaging = _signedData.SignedContent != null ? SignaturePackaging.ATTACHED_IMPLICIT : SignaturePackaging.DETACHED_EXPLICIT;
     ReadSignersInfo();
 }
예제 #6
0
        public Queue <string> GetSignersCommonNames(CmsSignedData cms)
        {
            var lst = new Queue <string>();

            var store = cms.GetCertificates("COLLECTION");

            var signers = cms.GetSignerInfos();

            foreach (var sig in signers.GetSigners())
            {
                var signer = (SignerInformation)sig;

                foreach (var st in store.GetMatches(signer.SignerID))
                {
                    var crt = (X509Certificate)st;

                    var dn = crt.SubjectDN.ToString();

                    var regex = new Regex(@"^CN=|,\S.*");

                    var commonName = regex.Replace(dn, "");

                    lst.Enqueue(commonName);
                }
            }

            return(lst);
        }
예제 #7
0
        /// <summary>
        /// Verifies if the ETK contains a token that is still valid and can be trusted.
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method checks if the certificate in the ETK is issued by a trusted party.  Trust means
        /// the root certificate is trusted by the computer it is running on and all
        /// validation checks, including revocation, are successful.  Root
        /// certificates are trusted by the computer if present in the
        /// <see cref="StoreName.Root"/> store.
        /// </para>
        /// <para>
        /// This method no longer validates the signer of the ETK token due lack of signing time in the ETK.
        /// The encryption certificate inside the ETK is still completely verified, this means there isn't a reduction in
        /// security compared to the previous implementation.
        /// </para>
        /// </remarks>
        /// <param name="checkRevocation"><c>true</c>to check if the certificates that issued the encryption cert aren't revoked</param>
        /// <returns>Detailed information about the encryption certificate status</returns>
        public CertificateSecurityInformation Verify(bool checkRevocation)
        {
            IList <CertificateList>   crls;
            IList <BasicOcspResponse> ocps;

            //Get encryption cert
            BC::X509Certificate encCert = DotNetUtilities.FromX509Certificate(ToCertificate());

            trace.TraceEvent(TraceEventType.Information, 0, "Verifying ETK: {0}", encCert.SubjectDN.ToString());

            //Check the certificate
            IX509Store certs = raw.GetCertificates("COLLECTION");

            if (checkRevocation)
            {
                crls = new List <CertificateList>();
                ocps = new List <BasicOcspResponse>();
            }
            else
            {
                crls = null;
                ocps = null;
            }
            CertificateSecurityInformation certInfo = encCert.Verify(DateTime.UtcNow, new int[] { 2, 3 }, EteeActiveConfig.Unseal.MinimumEncryptionKeySize.AsymmerticRecipientKey, certs, ref crls, ref ocps);

            if (!(encCert.GetPublicKey() is RsaKeyParameters))
            {
                certInfo.securityViolations.Add(CertSecurityViolation.NotValidKeyType);
                trace.TraceEvent(TraceEventType.Warning, 0, "Only RSA keys can be used for sealing");
            }
            return(certInfo);
        }
예제 #8
0
        public static bool ValidateSignature(byte[] messageBytes, byte[] signatureBytes, X509Certificate certificate)
        {
            CmsProcessable         signedContent    = new CmsProcessableByteArray(messageBytes);
            CmsSignedData          signedData       = new CmsSignedData(signedContent, signatureBytes);
            IX509Store             certificateStore = signedData.GetCertificates("Collection");
            SignerInformationStore signerInfoStore  = signedData.GetSignerInfos();
            ICollection            signers          = signerInfoStore.GetSigners();

            foreach (SignerInformation signer in signers)
            {
                bool isChainValid = ValidateCertificateChain(certificateStore, signer.SignerID);
                if (!isChainValid)
                {
                    return(false);
                }

                bool verified = signer.Verify(certificate);
                if (!verified)
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #9
0
        internal X509Certificate GenerateCertificate(String certificateString)
        {
            X509Certificate x509Certificate = null;

            try
            {
                byte[]        bytes         = Convert.FromBase64CharArray(certificateString.ToCharArray(), 0, certificateString.Length);
                CmsSignedData cmsSignedData = new CmsSignedData(bytes);

                IX509Store  store           = cmsSignedData.GetCertificates("Collection");
                ICollection allCertificates = store.GetMatches(null);

                IEnumerator enumerator = allCertificates.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    x509Certificate = (X509Certificate)enumerator.Current;
                    Console.WriteLine("Server Generated Certificate: " + x509Certificate.ToString());
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Certificate generation error: " + ex);
                throw new Exception("Certificate generation error");
            }
            return(x509Certificate);
        }
예제 #10
0
        /*
         * /// <exception cref="System.IO.IOException"></exception>
         * public override Document ExtendDocument(Document document, Document originalDocument
         *  , SignatureParameters parameters)
         * {
         *  CAdESSignatureExtension extension = GetExtensionProfile(parameters);
         *  if (extension != null)
         *  {
         *      return extension.ExtendSignatures(document, originalDocument, parameters);
         *  }
         *  else
         *  {
         *      //LOG.Info("No extension for " + parameters.SignatureFormat);
         *  }
         *  return document;
         * }
         */

        private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ISignatureFactory factory,
                                                                    SignatureParameters parameters, CAdESProfileBES cadesProfile,
                                                                    bool includeUnsignedAttributes, CmsSignedData originalSignedData
                                                                    )
        {
            var signedAttrGen = new DefaultSignedAttributeTableGenerator(
                new AttributeTable(cadesProfile.GetSignedAttributes(parameters)));

            SimpleAttributeTableGenerator unsignedAttrGen = null;

            if (includeUnsignedAttributes)
            {
                var attributes = cadesProfile.GetUnsignedAttributes(parameters);
                if (attributes.Count != 0)
                {
                    unsignedAttrGen = new SimpleAttributeTableGenerator(new AttributeTable(attributes));
                }
            }

            SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();

            sigInfoGeneratorBuilder.WithSignedAttributeGenerator(signedAttrGen);
            if (unsignedAttrGen != null)
            {
                sigInfoGeneratorBuilder.WithUnsignedAttributeGenerator(unsignedAttrGen);
            }

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSignerInfoGenerator(sigInfoGeneratorBuilder.Build(factory, parameters.SigningCertificate));

            if (originalSignedData != null)
            {
                generator.AddSigners(originalSignedData.GetSignerInfos());
            }

            var certs = new List <X509Certificate>();

            certs.Add(parameters.SigningCertificate);
            if (parameters.CertificateChain != null)
            {
                foreach (X509Certificate cert in parameters.CertificateChain)
                {
                    if (!cert.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN))
                    {
                        certs.Add(cert);
                    }
                }
            }
            IX509Store certStore = X509StoreFactory.Create("Certificate/Collection",
                                                           new X509CollectionStoreParameters(certs));

            generator.AddCertificates(certStore);
            if (originalSignedData != null)
            {
                generator.AddCertificates(originalSignedData.GetCertificates("Collection"));
            }

            return(generator);
        }
        public static void ReadXmlSigned(this Fattura 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);
            }
        }
예제 #12
0
        // https://github.com/joschi/cryptoworkshop-bouncycastle/blob/master/src/main/java/cwguide/BcSignedDataExample.java
        public static void foo()
        {
            byte[] data = null;
            Org.BouncyCastle.Cms.CmsSignedData signedData = new CmsSignedData(data);

            byte[] content = signedData.SignedContent.GetContent() as byte[];

            Org.BouncyCastle.X509.Store.IX509Store certs = signedData.GetCertificates("type");
        }
예제 #13
0
        /// <summary>
        /// Método para crear el generador de firmas
        /// </summary>
        /// <param name="signerProvider"></param>
        /// <param name="parameters"></param>
        /// <param name="originalSignedData"></param>
        /// <returns></returns>
        private CustomCMSSignedDataGenerator CreateSignedGenerator(ISigner signerProvider,
                                                                   SignatureParameters parameters, CmsSignedData originalSignedData)
        {
            X509CertificateParser parser = new X509CertificateParser();
            var signerCertificate        = parser.ReadCertificate(parameters.Certificate.GetRawCertData());

            CustomCMSSignedDataGenerator generator = new CustomCMSSignedDataGenerator();

            Dictionary <DerObjectIdentifier, Asn1Encodable> signedAttrDic = GetSignedAttributes(parameters);

            if (!signedAttrDic.ContainsKey(PkcsObjectIdentifiers.IdAAContentHint) &&
                originalSignedData != null)
            {
                var attrContentHint = GetContentHintAttribute(originalSignedData.GetSignerInfos());

                if (attrContentHint != null)
                {
                    signedAttrDic.Add(PkcsObjectIdentifiers.IdAAContentHint, attrContentHint);
                }
            }

            CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator
                                                           (new Org.BouncyCastle.Asn1.Cms.AttributeTable(signedAttrDic));

            generator.SignerProvider = signerProvider;
            generator.AddSigner(new NullPrivateKey(), signerCertificate,
                                PkcsObjectIdentifiers.RsaEncryption.Id, parameters.DigestMethod.Oid, signedAttrGen, null);

            if (originalSignedData != null)
            {
                generator.AddSigners(originalSignedData.GetSignerInfos());
            }

            bool addSignerCert = true;

            if (originalSignedData != null)
            {
                IX509Store originalCertStore = originalSignedData.GetCertificates("Collection");

                generator.AddCertificates(originalCertStore);

                addSignerCert = !CheckCertExists(signerCertificate, originalCertStore);
            }

            if (addSignerCert)
            {
                List <X509Certificate> certs = new List <X509Certificate>();
                certs.Add(signerCertificate);

                IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));
                generator.AddCertificates(certStore);
            }

            return(generator);
        }
예제 #14
0
        static void Main(string[] args)
        {
            //if (args.Length > 0)
            //string fullFileName = Path.GetFullPath(args[0]);
            foreach (string fileName in Directory.GetFiles("p7m"))
            {
                FileStream file    = new FileStream(fileName, FileMode.Open);
                bool       isValid = true;
                Console.WriteLine("File to decrypt: " + fileName);
                try
                {
                    CmsSignedData          signedFile  = new CmsSignedData(file);
                    IX509Store             certStore   = signedFile.GetCertificates("Collection");
                    ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
                    SignerInformationStore signerStore = signedFile.GetSignerInfos();
                    ICollection            signers     = signerStore.GetSigners();

                    foreach (object tempCertification in certs)
                    {
                        X509Certificate certification = tempCertification as X509Certificate;

                        foreach (object tempSigner in signers)
                        {
                            SignerInformation signer = tempSigner as SignerInformation;
                            if (!signer.Verify(certification.GetPublicKey()))
                            {
                                isValid = false;
                                break;
                            }
                        }
                    }
                    string newFileName = Path.Combine(Directory.CreateDirectory("p7m-extracted").Name, Path.GetFileNameWithoutExtension(fileName));
                    using (var fileStream = new FileStream(newFileName, FileMode.Create, FileAccess.Write))
                    {
                        signedFile.SignedContent.Write(fileStream);
                        Console.WriteLine("File decrypted: " + newFileName);
                    }
                }
                catch (Exception ex)
                {
                    isValid = false;
                }

                Console.WriteLine("File valid: " + isValid);

                ;
            }
            Console.ReadLine();
        }
예제 #15
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> list = new List <X509Certificate>();

            if (!onlyExtended)
            {
                logger.Info(cmsSignedData.GetCertificates("Collection").GetMatches(null).Count + " certificate in collection");
                foreach (X509Certificate ch in cmsSignedData.GetCertificates("Collection").GetMatches(null))
                {
                    X509Certificate c = ch;
                    logger.Info("Certificate for subject " + c.SubjectDN);
                    if (!list.Contains(c))
                    {
                        list.Add(c);
                    }
                }
            }
            // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
            SignerInformation si = BCStaticHelpers.GetSigner(cmsSignedData, signerId);

            if (si != null && si.UnsignedAttributes != null && si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues] != null)
            {
                DerSequence seq = (DerSequence)si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues].AttrValues[0];
                for (int i = 0; i < seq.Count; i++)
                {
                    X509CertificateStructure cs = X509CertificateStructure.GetInstance(seq[i]);
                    X509Certificate          c  = new X509Certificate(cs);
                    if (!list.Contains(c))
                    {
                        list.Add(c);
                    }
                }
            }

            return(list);
        }
        /// <summary>
        /// Extracts a certificate chain from PKCS#7 CMS payload encoded in PEM.
        /// </summary>
        /// <param name="pemEncodedPkcs7">The payload containing the PKCS#7 CMS data.</param>
        /// <remarks>
        /// The method is expecting a PKCS#7/CMS SignedData structure containing no "content" and zero SignerInfos.
        /// </remarks>
        /// <returns>
        /// The certificate chain contained in the specified payload.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="pemEncodedPkcs7"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="pemEncodedPkcs7"/> is white space.</exception>
        public static IReadOnlyList <X509Certificate> ReadCertChainFromPemEncodedPkcs7CmsString(
            string pemEncodedPkcs7)
        {
            new { pemEncodedPkcs7 }.Must().NotBeNullNorWhiteSpace();

            IReadOnlyList <X509Certificate> result;

            using (var stringReader = new StringReader(pemEncodedPkcs7))
            {
                var pemReader = new PemReader(stringReader);
                var pemObject = pemReader.ReadPemObject();
                var data      = new CmsSignedData(pemObject.Content);
                var certStore = data.GetCertificates("COLLECTION");
                result = certStore.GetMatches(null).Cast <X509Certificate>().ToList();
            }

            return(result);
        }
예제 #17
0
        private static X509Certificate GenerateCertificate(String certificateString)
        {
            byte[]        bytes         = Convert.FromBase64CharArray(certificateString.ToCharArray(), 0, certificateString.Length);
            CmsSignedData cmsSignedData = new CmsSignedData(bytes);

            IX509Store  store           = cmsSignedData.GetCertificates("Collection");
            ICollection allCertificates = store.GetMatches(null);

            IEnumerator enumerator = allCertificates.GetEnumerator();

            while (enumerator.MoveNext())
            {
                X509Certificate x509 = (X509Certificate)enumerator.Current;
                Console.WriteLine("Server Generated Certificate: " + x509.ToString());
                return(x509);
            }
            throw new Exception("Certificate generation error");
        }
        // taken from bouncy castle SignedDataTest.cs
        private static bool VerifySignatures(
            CmsSignedData sp)
        {
            var                    signaturesValid = true;
            IX509Store             x509Certs       = sp.GetCertificates("Collection");
            SignerInformationStore signers         = sp.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)certEnum.Current;

                signaturesValid &= signer.Verify(cert);
            }
            return(signaturesValid);
        }
예제 #19
0
        public static byte[] VerifySignature(CmsSignedData cms)
        {
            var store = cms.GetCertificates("COLLECTION");

            var signers = cms.GetSignerInfos();

            byte[] arr;

            using (var stream = new MemoryStream())
            {
                cms.SignedContent.Write(stream);

                arr = stream.ToArray();
            }

            foreach (var sig in signers.GetSigners())
            {
                var signer = (SignerInformation)sig;

                foreach (var st in store.GetMatches(signer.SignerID))
                {
                    var crt = (X509Certificate)st;

                    CheckCertificateValidity(crt);

                    var gst = new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411_2012_256Digest());

                    gst.Init(false, crt.GetPublicKey());

                    gst.BlockUpdate(arr, 0, arr.Length);

                    var t = gst.VerifySignature(signer.GetSignature());

                    if (!t)
                    {
                        throw new CryptographicException("Cannot verify signature");
                    }
                }
            }

            return(arr);
        }
예제 #20
0
        public static byte[] getHashFromSignature(byte[] signature)
        {
            CmsSignedData content = new CmsSignedData(signature);

            byte[] retval = null;
            try
            {
                SignerInformationStore sistore = content.GetSignerInfos();
                foreach (SignerInformation signer in sistore.GetSigners())
                {
                    if (signer.SignedAttributes != null)
                    {
                        if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest] != null)
                        {
                            Asn1Encodable enc = signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest].AttrValues[0];
                            retval = Org.BouncyCastle.Asn1.Asn1OctetString.GetInstance(enc).GetOctets();
                        }
                    }
                    else
                    {
                        IX509Store  store     = content.GetCertificates("Collection");
                        ICollection certsColl = store.GetMatches(null);
                        foreach (Org.BouncyCastle.X509.X509Certificate cert in certsColl)
                        {
                            signer.Verify(cert);
                            retval = signer.GetContentDigest();
                            break;
                        }
                    }
                    if (retval != null)
                    {
                        return(retval);
                    }
                }
            }
            catch
            {
                return(getSha256(extractSignedContent(signature)));
            }

            return(null);
        }
예제 #21
0
        public void verify(byte[] byte_pdfData, X509Certificate2 trustCert, string signatureName)
        {
            PdfReader pdfReader = new PdfReader(byte_pdfData);

            AcroFields acroField = pdfReader.AcroFields;

            if (signatureName == null || "".CompareTo(signatureName) != 0)
            {
                signatureName = acroField.GetSignatureNames().Last();
            }

            PdfPKCS7 pdfP7 = acroField.VerifySignature(signatureName);

            if (pdfP7 == null)
            {
                throw new NullReferenceException("Invalid signatureName:" + signatureName);
            }

            if (!pdfP7.Verify())
            {
                throw new PdfException("Unable to verify specified signature field, specify signature invalid");
            }

            byte[]        pkcs7Signatue = pdfP7.GetEncodedPKCS7();
            CmsSignedData signedData    = new CmsSignedData(pkcs7Signatue);

            // Get signer certificate from CMSSignedData
            IX509Store  x509Certs = signedData.GetCertificates("Collection");
            ICollection cerlist   = x509Certs.GetMatches(null);
            IEnumerator cEnum     = cerlist.GetEnumerator();
            ArrayList   _chain    = new ArrayList();

            while (cEnum.MoveNext())
            {
                Org.BouncyCastle.X509.X509Certificate cer = (Org.BouncyCastle.X509.X509Certificate)cEnum.Current;
                X509Certificate2 cer2 = new X509Certificate2(cer.GetEncoded());
                _chain.Add(cer2);
            }

            X509Certificate2[] certChain = (X509Certificate2[])_chain.ToArray(typeof(X509Certificate2));
            validateSignature(signedData, certChain[0]);
        }
예제 #22
0
        private CmsSignedDataGenerator CreateCMSSignedDataGenerator(SignatureParameters parameters, CAdESProfileBES cadesProfile, bool includeUnsignedAttributes = true, CmsSignedData originalSignedData = null, byte[] signature = null)
        {
            CmsSignedDataGenerator generator         = new CmsSignedDataGenerator();
            X509Certificate        signerCertificate = parameters.SigningCertificate;

            CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator(new AttributeTable(cadesProfile.GetSignedAttributes(parameters) as System.Collections.IDictionary));

            CmsAttributeTableGenerator unsignedAttrGen = new SimpleAttributeTableGenerator(includeUnsignedAttributes ? new AttributeTable(cadesProfile.GetUnsignedAttributes(parameters) as System.Collections.IDictionary) : null);

            var builder = new SignerInfoGeneratorBuilder().WithSignedAttributeGenerator(signedAttrGen).WithUnsignedAttributeGenerator(unsignedAttrGen);

            generator.AddSignerInfoGenerator(builder.Build(new ReadySignatureFactory(new PreComputedSigner(signature), parameters.DigestWithEncriptionOID), signerCertificate));

            if (originalSignedData != null)
            {
                generator.AddSigners(originalSignedData.GetSignerInfos());
            }
            var certs = new List <X509Certificate>
            {
                parameters.SigningCertificate
            };

            if (parameters.CertificateChain != null)
            {
                foreach (X509Certificate c in parameters.CertificateChain)
                {
                    if (!c.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN))
                    {
                        certs.Add(c);
                    }
                }
            }
            IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));

            generator.AddCertificates(certStore);
            if (originalSignedData != null)
            {
                generator.AddCertificates(originalSignedData.GetCertificates("Collection"));
            }
            return(generator);
        }
        public void TestSignHashWithBouncyCastle()
        {
            byte[] hashBytes = System.Convert.FromBase64String(Base64encodedHashToSign);

            byte[] signedCmsData = SignatureProvider.SignatureProvider.Sign(hashBytes, SignerName, SignerEmail, SignerCountry, SignerOrganization);

            CmsSignedData          cmsSignedData = new CmsSignedData(signedCmsData);
            IX509Store             x509Certs     = cmsSignedData.GetCertificates("Collection");
            SignerInformationStore signers       = cmsSignedData.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                Assert.AreEqual(1, certCollection.Count);

                IEnumerator certEnum = certCollection.GetEnumerator();
                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                Assert.AreEqual(cert.SubjectDN.ToString(), "CN=Cyril Thirion,E=cyril.thirion\\[email protected],C=FR,O=Acme");

                Assert.AreEqual(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtContentType].AttrValues[0].ToString(), PkcsObjectIdentifiers.Data.ToString());
                Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest]);
                Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]);
                Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime]);

                Assert.AreEqual(
                    "#" + BitConverter.ToString(hashBytes).Replace("-", ""),
                    signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest].AttrValues[0].ToString(), true
                    );

                byte[] signedData = signer.GetEncodedSignedAttributes();
                System.IO.File.WriteAllBytes("/tmp/tmp.txt", signedData);
                ISigner s = SignerUtilities.GetSigner("SHA256withRSA");
                s.Init(false, cert.GetPublicKey());
                s.BlockUpdate(signedData, 0, signedData.Length);
                Assert.IsTrue(s.VerifySignature(signer.GetSignature()), "Signature verification failed.");
            }
        }
        public static void ReadXmlSigned(this Fattura fattura, string filePath)
        {
            CmsSignedData          signedFile  = new CmsSignedData(new FileStream(filePath, FileMode.Open, FileAccess.Read));
            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);
                    }
                }
            }


            string outFile = Path.GetTempFileName();

            using (var fileStream = new FileStream(outFile, FileMode.Create, FileAccess.Write))
            {
                signedFile.SignedContent.Write(fileStream);
            }

            using (var r = XmlReader.Create(outFile, new XmlReaderSettings {
                IgnoreWhitespace = true, IgnoreComments = true
            }))
            {
                fattura.ReadXml(r);
            }
        }
예제 #25
0
		private void VerifySignatures(CmsSignedData s, byte[] contentDigest)
		{
			IX509Store x509Certs = s.GetCertificates("Collection");
			IX509Store x509Crls = s.GetCrls("Collection");
			SignerInformationStore signers = s.GetSignerInfos();

			foreach (SignerInformation signer in signers.GetSigners())
			{
				ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

				IEnumerator certEnum = certCollection.GetEnumerator();

				certEnum.MoveNext();
				X509Certificate cert = (X509Certificate) certEnum.Current;

				VerifySigner(signer, cert);

				if (contentDigest != null)
				{
					Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
				}
			}

			ICollection certColl = x509Certs.GetMatches(null);
			ICollection crlColl = x509Crls.GetMatches(null);

			Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count);
			Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count);
		}
예제 #26
0
        static void PKCS7()
        {
            GostCryptoConfig.ProviderType = ProviderTypes.VipNet;
            Config.InitCommon();

            BCX509.X509Certificate bcCert = null;
            using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm())
            {
                bool   detached = false;
                byte[] data     = File.ReadAllBytes("test.xml");

                var certBytes = g.ContainerCertificateRaw;

                BCX509.X509CertificateParser _x509CertificateParser = new BCX509.X509CertificateParser();
                bcCert = _x509CertificateParser.ReadCertificate(certBytes);

                ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>();
                certPath.Add(bcCert);

                IDigest digest  = new Gost3411Digest();
                string  hashOid = GostCryptoConfig.DefaultHashOid;

                byte[] dataHash = ComputeDigest(digest, data);

                // Construct SignerInfo.signedAttrs
                Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector();

                // Add PKCS#9 contentType signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.3"),
                        new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1"))));

                // Add PKCS#9 messageDigest signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.4"),
                        new DerSet(new DerOctetString(dataHash))));

                // Add PKCS#9 signingTime signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.5"),
                        new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow)))));

                DerSet signedAttributes = new DerSet(signedAttributesVector);
                byte[] pkcs1Digest      = ComputeDigest(digest, signedAttributes.GetDerEncoded());
                byte[] pkcs1DigestInfo  = CreateDigestInfo(pkcs1Digest, hashOid);

                // hash


                //var signature = g.CreateSignature(hash);
                var formatter = new GostSignatureFormatter(g);
                var signature = formatter.CreateSignature(pkcs1Digest);

                // Construct SignerInfo
                SignerInfo signerInfo = new SignerInfo(
                    new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)),
                    new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null),
                    signedAttributes,
                    new AlgorithmIdentifier(new DerObjectIdentifier(GostCryptoConfig.DefaultSignOid), null),
                    new DerOctetString(signature),
                    null);

                // Construct SignedData.digestAlgorithms
                Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();
                digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null));

                // Construct SignedData.encapContentInfo
                ContentInfo encapContentInfo = new ContentInfo(
                    new DerObjectIdentifier("1.2.840.113549.1.7.1"),
                    (detached) ? null : new DerOctetString(data));

                // Construct SignedData.certificates
                Asn1EncodableVector certificatesVector = new Asn1EncodableVector();
                foreach (BCX509.X509Certificate cert in certPath)
                {
                    certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
                }

                // Construct SignedData.signerInfos
                Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();
                signerInfosVector.Add(signerInfo.ToAsn1Object());

                // Construct SignedData
                SignedData signedData = new SignedData(
                    new DerSet(digestAlgorithmsVector),
                    encapContentInfo,
                    new BerSet(certificatesVector),
                    null,
                    new DerSet(signerInfosVector));

                // Construct top level ContentInfo
                ContentInfo contentInfo = new ContentInfo(
                    new DerObjectIdentifier("1.2.840.113549.1.7.2"),
                    signedData);

                var res = contentInfo.GetDerEncoded();
                File.WriteAllBytes("test.p7", res);


                CmsSignedData cms = new CmsSignedData(res);

                var certStore = cms.GetCertificates("Collection");


                SignerInformationStore signers = cms.GetSignerInfos();
                var it = signers.GetSigners().GetEnumerator();
                it.MoveNext();
                var signer = it.Current as SignerInformation;

                var b = signer.Verify(bcCert);
            }
        }
        private SignaturesResult VerifyP7m(byte[] barr, string fileName)
        {
            //System.Diagnostics.Trace.WriteLine(string.Format("Verifica firme del file {0} ...",
            //System.IO.Path.GetFileName(fileName)));
            var result = new SignaturesResult();

            result.SignatureInfos = new List <SignatureInfo>();
            try
            {
                var estensione = System.IO.Path.GetExtension(fileName).ToLower();
                var nomeFile   = System.IO.Path.GetFileName(fileName);
                while (estensione == ".p7m")
                {
                    Org.BouncyCastle.Cms.CmsSignedData cms = new CmsSignedData(barr);
                    var certs = cms.GetCertificates("Collection");
                    var sis   = cms.GetSignerInfos();
                    if (sis != null)
                    {
                        if (RecursiveP7m || ExtractSignedContent)
                        {
                            using (var ms = new MemoryStream())
                            {
                                cms.SignedContent.Write(ms);
                                barr = ms.ToArray();
                            }
                            if (ExtractSignedContent)
                            {
                                result.SignedContent = barr;
                            }
                        }

                        var signers = sis.GetSigners();
                        foreach (SignerInformation sign in signers)
                        {
                            var si = new SignatureInfo();

                            DateTime?dt  = null;
                            var      aaa = sign.SignedAttributes[CmsAttributes.SigningTime];
                            if (aaa != null && aaa.AttrValues != null && aaa.AttrValues.Count > 0)
                            {
                                var st = aaa.AttrValues[0] as DerUtcTime;
                                if (st != null)
                                {
                                    dt = st.ToAdjustedDateTime();
                                }
                            }
                            if (dt == null)
                            {
                                throw new Exception("Impossibile ricavare SignDateTime.");
                            }
                            si.SignDateTime = dt.Value;

                            //si.FilterSubtype=
                            IList ccc = new ArrayList(certs.GetMatches(null));
                            List <Org.BouncyCastle.X509.X509Certificate> list =
                                new List <Org.BouncyCastle.X509.X509Certificate>();
                            foreach (var c in ccc)
                            {
                                list.Add(c as Org.BouncyCastle.X509.X509Certificate);
                            }
                            var errors =
                                iTextSharp.text.pdf.security.CertificateVerification.VerifyCertificates(
                                    list, keyStore, si.SignDateTime);
                            if (errors.Count > 0)
                            {
                                si.ChainCertificatesNotValidAtSignedTime = true;
                            }

                            IList cs = new ArrayList(certs.GetMatches(sign.SignerID));
                            var   cc = (Org.BouncyCastle.X509.X509Certificate)cs[0];
                            si.DigestAlgorithm = cc.SigAlgName;
                            //si.EncryptionAlgorithm = sign.EncryptionAlgorithmID.ToString();
                            si.IntegrityValid = sign.Verify(cc);

                            X509Certificate2 cert2 = new X509Certificate2(cc.GetEncoded());
                            si.Name     = null;
                            si.Signer   = cert2.SubjectName.Name;
                            si.Revision = sign.Version;
                            if (CheckRevocation)
                            {
                                try
                                {
                                    //si.CertificateRevocatedAtSignedTime = pkcs7.IsRevocationValid();
                                    List <Org.BouncyCastle.Ocsp.BasicOcspResp> ocsps =
                                        new List <Org.BouncyCastle.Ocsp.BasicOcspResp>();
                                    //if (cc.Ocsp != null)
                                    //    ocsps.Add(pkcs7.Ocsp);
                                    iTextSharp.text.pdf.security.OcspVerifier ocspVerifier = new OcspVerifier(null,
                                                                                                              ocsps);
                                    var issueCert =
                                        keyStore.SingleOrDefault(
                                            c => c.SubjectDN.Equals(cc.IssuerDN));
                                    if (issueCert == null)
                                    {
                                        throw new Exception("Issuer certificate not found.");
                                    }
                                    List <VerificationOK> verification = ocspVerifier.Verify(
                                        cc,
                                        issueCert,
                                        si.SignDateTime);
                                    if (verification.Count == 0)
                                    {
                                        var         crls        = new List <Org.BouncyCastle.X509.X509Crl>();
                                        CrlVerifier crlVerifier = new CrlVerifier(null, crls);
                                        crlVerifier.OnlineCheckingAllowed = true;
                                        verification = crlVerifier.Verify(cc, issueCert,
                                                                          si.SignDateTime);
                                    }
                                    if (verification.Count == 0)
                                    {
                                        si.CertificateRevocatedAtSignedTime = null;
                                    }
                                    else
                                    {
                                        si.CertificateRevocatedAtSignedTime = false;
                                        foreach (var verificationOk in verification)
                                        {
                                            System.Diagnostics.Trace.WriteLine(verificationOk);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    si.CertificateRevocatedAtSignedTime = true; // o null?
                                    System.Diagnostics.Trace.WriteLine(
                                        string.Format(
                                            "Si è verificato il seguente errore durante la verifica di revoca per la firma {2}  del file {0} {1}",
                                            System.IO.Path.GetFileName(fileName), ex.Message, si.Revision));
                                }
                            }
                            si.SignatureValid = si.IntegrityValid &&
                                                !si.ChainCertificatesNotValidAtSignedTime &&
                                                (!CheckRevocation || !si.CertificateRevocatedAtSignedTime.GetValueOrDefault(true));

                            result.SignatureInfos.Add(si);
                        }
                    }

                    if (!RecursiveP7m)
                    {
                        break;
                    }

                    nomeFile   = System.IO.Path.GetFileNameWithoutExtension(nomeFile);
                    estensione = System.IO.Path.GetExtension(nomeFile);
                }

                result.SignaturesValid = result.SignatureInfos.All(si => si.SignatureValid);

                //System.Diagnostics.Trace.WriteLine(string.Format(
                //    "Verifica firme del file {0} completata con esito {1}", System.IO.Path.GetFileName(fileName),
                //    result.SignaturesValid ? "Positivo" : "Negativo"));
            }
            catch (Exception exx)
            {
                System.Diagnostics.Trace.WriteLine(
                    string.Format(
                        "Si è verificato il seguente errore durante la verifica delle firme del file {0} {1}",
                        System.IO.Path.GetFileName(fileName), exx.Message));
                throw exx;
            }

            return(result);
        }
 public IX509Store GetCertificates(string type)
 {
     return(tsToken.GetCertificates(type));
 }
예제 #29
0
        /// <summary>
        /// Adds or removes Content to P7mFile
        /// </summary>
        /// <param name="CmsData">Signature Info</param>
        /// <param name="File">File, if null returns only Signature Info</param>
        /// <returns></returns>
        public static byte[] EmbedFileToPkcs(byte[] CmsData, byte[] File)
        {
            DerObjectIdentifier contentTypeOID = CmsObjectIdentifiers.Data;
            Asn1EncodableVector digestAlgs     = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos    = new Asn1EncodableVector();
            Asn1OctetString     octs           = null;

            if (File != null)
            {
                octs = new DerOctetString(File);
            }
            Org.BouncyCastle.Asn1.Cms.ContentInfo encInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(contentTypeOID, octs);

            CmsProcessable content = new CmsProcessableByteArray(CmsData);

            Asn1Set     certificates = null;
            Asn1Set     certrevlist  = null;
            ArrayList   _certs       = new ArrayList();
            ArrayList   _crls        = new ArrayList();
            ICollection certsColl    = new ArrayList();
            ICollection crlsColl     = new ArrayList();

            CmsSignedData          cms     = new CmsSignedData(CmsData);
            SignerInformationStore signers = cms.GetSignerInfos();
            IX509Store             store   = cms.GetCertificates("Collection");
            IX509Store             crls    = cms.GetCrls("Collection");

            certsColl = store.GetMatches(null);
            crlsColl  = crls.GetMatches(null);
            foreach (SignerInformation signer in signers.GetSigners())
            {
                //digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
                digestAlgs.Add(signer.DigestAlgorithmID);
                signerInfos.Add(signer.ToSignerInfo());
            }
            foreach (Org.BouncyCastle.X509.X509Certificate cert in certsColl)
            {
                _certs.Add(Asn1Object.FromByteArray(cert.GetEncoded()));
            }

            foreach (Org.BouncyCastle.X509.X509Certificate clr in crlsColl)
            {
                _crls.Add(Asn1Object.FromByteArray(clr.GetEncoded()));
            }

            if (_certs.Count != 0)
            {
                certificates = CreateBerSetFromList(_certs);
            }

            if (_crls.Count != 0)
            {
                certrevlist = CreateBerSetFromList(_crls);
            }

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(CmsObjectIdentifiers.SignedData, sd);
            byte[] retval = new CmsSignedData(content, contentInfo.GetDerEncoded()).GetEncoded();
            string asn    = BitConverter.ToString(retval).Replace("-", "");

            return(retval);
        }
예제 #30
0
        /// <summary>
        /// Verify PKCS7 signature
        /// </summary>
        /// <returns>CAPICOM/CryptoAPI return code or an ApplicationException in file hash doesn't match</returns>
        public bool Verify(ref List <string> ErrorMessageLst)
        {
            bool rc = true;

            //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - INIT");
            try
            {
                // Decodifica un messaggio SignedCms codificato.
                // Al completamento della decodifica, è possibile recuperare le
                // informazioni decodificate dalle proprietà dell'oggetto SignedCms.
                CmsSignedData          cms     = new CmsSignedData(this.GetSignedContent(this._buf));
                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)
                {
                    this._SignAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID);
                }


                //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - Decode signed message");

                //  Verify signature. Do not validate signer
                //  certificate for the purposes of this example.
                //  Note that in a production environment, validating
                //  the signer certificate chain will probably
                //  be necessary.

                /*
                 * verifica le firme digitali nel messaggio CMS/PKCS #7 firmato e,
                 * facoltativamente, convalida i certificati del firmatario.
                 *
                 * * Se verifySignatureOnly è true, vengono verificate solo le firme digitali.
                 * Se è false, vengono verificate le firme digitali e vengono convalidati
                 * i certificati dei firmatari e gli scopi dei certificati.
                 * Gli scopi di un certificato sono considerati validi se il certificato
                 * non prevede l'utilizzo della chiave o se l'utilizzo della chiave supporta
                 * le firme digitali o il non-rifiuto.
                 *
                 */
                //_signersInfo = new DocsPaVO.documento.SignerInfo[signers.GetSigners().Count];
                //int i = 0;

                List <DocsPaVO.documento.SignerInfo> signInfoLst = new List <DocsPaVO.documento.SignerInfo>();
                foreach (SignerInformation signer in signers.GetSigners())
                {
                    DocsPaVO.documento.SignerInfo thisSinger = ExtractSignerInfo(ErrorMessageLst, store, signer);
                    signInfoLst.Add(thisSinger);
                }

                _signersInfo = signInfoLst.ToArray();
                //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - CheckSignature OK, signers count: {0}", signers.GetSigners().Count));
                CmsProcessable signedContent = cms.SignedContent;
                this._content = (byte[])signedContent.GetContent();

                if ((this._SignAlgorithm != null) && this._content != null)
                {
                    try
                    {
                        this._SignHash = BitConverter.ToString(Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(this._SignAlgorithm, this._content)).Replace("-", "");
                    }
                    catch (Exception e)
                    {
                        ErrorMessageLst.Add(e.Message);
                    }
                }

                //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - Extact content, lenght: {0}", this._content.Length));

                this._documentFileName = GetDocumentFileName();
                this._SignType         = "CADES";
                //DocsPaUtils.LogsManagement.Debugger.Write(string.Format("SignedDocument.Verify - DocumentFileName: '{0}'", this._documentFileName));
            }
            catch (Exception ex)
            {
                rc = false;
                //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - Si è verificato un errore nella verifica della firma", ex);
                //throw new ApplicationException(ex.Message);
                ErrorMessageLst.Add(ex.Message);
            }
            finally
            {
                //DocsPaUtils.LogsManagement.Debugger.Write("SignedDocument.Verify - END");
            }

            return(rc);
        }
예제 #31
0
        /// <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);
        }