/**
         * Generic validate function. Validates known types of xml signature.
         * @param fileName name of the signature file to be validated
         */
        public static void validate(String fileName)
        {
            Context context = new Context(Conn.ROOT_DIR + "efatura\\config\\");

            // add external resolver to resolve policies
            context.addExternalResolver(getPolicyResolver());

            XMLSignature signature = XMLSignature.parse(
                new FileDocument(new FileInfo(fileName)),
                context);

            ECertificate     cert = signature.SigningCertificate;
            ValidationSystem vs;

            if (cert.isMaliMuhurCertificate())
            {
                ValidationPolicy policy     = new ValidationPolicy();
                String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy-malimuhur.xml";
                policy = PolicyReader.readValidationPolicy(policyPath);
                vs     = CertificateValidation.createValidationSystem(policy);
                context.setCertValidationSystem(vs);
            }
            else
            {
                ValidationPolicy policy     = new ValidationPolicy();
                String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy.xml";
                policy = PolicyReader.readValidationPolicy(policyPath);
                vs     = CertificateValidation.createValidationSystem(policy);
                context.setCertValidationSystem(vs);
            }

            // no params, use the certificate in key info
            ValidationResult result = signature.verify();
            String           sonuc  = result.toXml();

            Console.WriteLine(result.toXml());
            // Assert.True(result.Type == ValidationResultType.VALID,"Cant verify " + fileName);

            UnsignedSignatureProperties usp = signature.QualifyingProperties.UnsignedSignatureProperties;

            if (usp != null)
            {
                IList <XMLSignature> counterSignatures = usp.AllCounterSignatures;
                foreach (XMLSignature counterSignature in counterSignatures)
                {
                    ValidationResult counterResult = signature.verify();

                    Console.WriteLine(counterResult.toXml());

                    //Assert.True(counterResult.Type == ValidationResultType.VALID,
                    //    "Cant verify counter signature" + fileName + " : "+counterSignature.Id);
                }
            }
        }
        /**
         * Validates given certificate
         */
        public static Boolean validateCertificate(ECertificate certificate)
        {
            try
            {
                ValidationSystem vs;
                // generate policy which going to be used in validation
                if (certificate.isMaliMuhurCertificate())
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy-malimuhur.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    vs     = CertificateValidation.createValidationSystem(policy);
                }
                else
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    vs     = CertificateValidation.createValidationSystem(policy);
                }
                vs.setBaseValidationTime(DateTime.UtcNow);

                // validate certificate
                CertificateStatusInfo csi = CertificateValidation.validateCertificate(vs, certificate);

                // return true if certificate is valid, false otherwise
                if (csi.getCertificateStatus() != CertificateStatus.VALID)
                {
                    return(false);
                }
                else if (csi.getCertificateStatus() == CertificateStatus.VALID)
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                throw new Exception("An error occured while validating certificate", e);
            }
            return(false);
        }
示例#3
0
        public ECertificate getEInvoiceCertificate(string pinNo)
        {
            if (mSignatureCert == null)
            {
                List <byte[]>       aCerts = bsc.getSignatureCertificates();
                List <ECertificate> certs  = new List <ECertificate>();

                foreach (byte[] bs in aCerts)
                {
                    ECertificate cert = new ECertificate(bs);

                    if (cert.isQualifiedCertificate())
                    {
                        certs.Add(cert);
                    }

                    else if (cert.isMaliMuhurCertificate())
                    {
                        certs.Add(cert);
                    }
                }
                if (certs.Count == 0)
                {
                    throw new ESYAException("Kartta fatura imzalayabiliceğiniz bir sertifika bulunmuyor");
                }
                else if (certs.Count == 1)
                {
                    mSignatureCert = certs[0];
                }
                else
                {
                    String[] optionList = new String[certs.Count];
                    for (int i = 0; i < certs.Count; i++)
                    {
                        if (certs[i].isQualifiedCertificate())
                        {
                            optionList[i] = certs[i].getSubject().getCommonNameAttribute() + " (Nitelikli)";
                        }
                        else
                        {
                            optionList[i] = certs[i].getSubject().getCommonNameAttribute() + " (MaliMühür)";
                        }
                    }

                    int result = askOption(null, null, optionList,
                                           "Sertifika Listesi", new String[] { "Tamam",
                                                                               "\u0130ptal" });

                    if (result < 0)
                    {
                        throw new ESYAException("Sertifika secmediniz");
                    }

                    else
                    {
                        mSignatureCert = certs[result];
                    }
                }
                return(mSignatureCert);
            }

            return(mSignatureCert);
        }
示例#4
0
        public static bool createEnvelopedBes(string pinNo, string signXML, String outXML, bool bInTest)
        {
            bool res = false;

            cardPinNo = pinNo;
            TestEnvelopedSignatureInitialize();
            try
            {
                // here is our custom envelope xml
                //  XmlDocument envelopeDoc = newEnvelope("edefter.xml");


                XmlDocument envelopeDoc = Conn.newEnvelope(signXML);
                XmlElement  exts        = (XmlElement)envelopeDoc.GetElementsByTagName("ext:UBLExtensions").Item(0);
                XmlElement  ext         = (XmlElement)exts.GetElementsByTagName("ext:UBLExtension").Item(0);
                XmlElement  extContent  = (XmlElement)ext.GetElementsByTagName("ext:ExtensionContent").Item(0);
                UriBuilder  ub          = new UriBuilder(Conn.ROOT_DIR + "efatura\\config\\");
                // create context with working dir
                Context context = new Context(ub.Uri);

                //UriBuilder ub2 = new UriBuilder(Conn.ROOT_DIR + "efatura\\config\\xmlsignature-config.xml");
                context.Config = new Config(Conn.ROOT_DIR + "efatura\\config\\xmlsignature-config.xml");

                // define where signature belongs to
                context.Document = envelopeDoc;

                // create signature according to context,
                // with default type (XADES_BES)
                XMLSignature signature = new XMLSignature(context, false);

                String setID = "Signature_" + envelopeDoc.GetElementsByTagName("cbc:ID").Item(0).InnerText;
                signature.Id          = setID;
                signature.SigningTime = DateTime.Now;

                // attach signature to envelope
                //envelopeDoc.DocumentElement.AppendChild(signature.Element);
                extContent.AppendChild(signature.Element);

                //add transforms for efatura
                Transforms transforms = new Transforms(context);
                transforms.addTransform(new Transform(context, TransformType.ENVELOPED.Url));


                // add document as reference,
                //signature.addDocument("#data1", "text/xml", false);
                signature.addDocument("", "text/xml", transforms, DigestMethod.SHA_256, false);

                ECertificate certificate = SmartCardManager.getInstance().getEInvoiceCertificate(cardPinNo);// getSignatureCertificate(true, false);
                if (certificate.isMaliMuhurCertificate())
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy-malimuhur.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    ValidationSystem vs = CertificateValidation.createValidationSystem(policy);
                    context.setCertValidationSystem(vs);
                }
                else
                {
                    ValidationPolicy policy     = new ValidationPolicy();
                    String           policyPath = Conn.ROOT_DIR + "efatura\\config\\certval-policy.xml";
                    policy = PolicyReader.readValidationPolicy(policyPath);
                    ValidationSystem vs = CertificateValidation.createValidationSystem(policy);
                    context.setCertValidationSystem(vs);
                }

                if (CertValidation.validateCertificate(certificate) || bInTest)
                {
                    BaseSigner signer = SmartCardManager.getInstance().getSigner(cardPinNo, certificate);

                    X509Certificate2 msCert = certificate.asX509Certificate2();
                    signature.addKeyInfo(msCert.PublicKey.Key);
                    signature.addKeyInfo(certificate);

                    KeyInfo keyInfo      = signature.createOrGetKeyInfo();
                    int     elementCount = keyInfo.ElementCount;
                    for (int k = 0; k < elementCount; k++)
                    {
                        KeyInfoElement kiElement = keyInfo.get(k);
                        if (kiElement.GetType().IsAssignableFrom(typeof(X509Data)))
                        {
                            X509Data        x509Data        = (X509Data)kiElement;
                            X509SubjectName x509SubjectName = new X509SubjectName(context,
                                                                                  certificate.getSubject().stringValue());
                            x509Data.add(x509SubjectName);
                            break;
                        }
                    }

                    //signature.addKeyInfo(certificate);

                    signature.SignedInfo.CanonicalizationMethod = C14nMethod.EXCLUSIVE_WITH_COMMENTS;

                    signature.sign(signer);

                    // this time we dont use signature.write because we need to write
                    // whole document instead of signature
                    using (Stream s = new FileStream(outXML, FileMode.Create))
                    {
                        try
                        {
                            envelopeDoc.Save(s);
                            s.Flush();
                            s.Close();

                            res = true;
                        }
                        catch (Exception e)
                        {
                            res = false;
                            MessageBox.Show("Dosya kaydedilirken hata oluştu " + e.Message.ToString());
                            s.Close();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                res = false;
                MessageBox.Show("Hata Oluştu \r\n" + e.Message.ToString());
            }

            return(res);
        }