예제 #1
0
        /**
         * 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);
                }
            }
        }
예제 #2
0
 /*
 ****************************************************************************
 * reset()
 ****************************************************************************
 */
 /**
 * Resets the internal state of this obj
 */
 public void reset()
 {
     msXmlID = "";
     msIssueInstant = "";
     moElem = null;
     moIssuer = null;
     moSignature = null;
     moSubject = null;
     moConditions = null;
     moAttrStatement = null;
 }
예제 #3
0
        /*
        ****************************************************************************
        * fromDOM()
        ****************************************************************************
        */
        /**
        *  This method populates the obj from DOM.  It does not keep a
        * copy of the DOM around.  Whitespace information is lost in this process.
        */
        public void fromDOM(XmlElement oElem)
        {
            reset();

            // get the id attribute
            if (oElem.hasAttributeNS(null, Tags.ATTR_ID_CAP))
            {
            msXmlID = oElem.getAttributeNS(null, Tags.ATTR_ID_CAP);
            }

            if (oElem.hasAttributeNS(null, Tags.ATTR_ISSUEINSTANT))
            {
            msIssueInstant = oElem.getAttributeNS(null, Tags.ATTR_ISSUEINSTANT);
            }

            for (
            XmlNode oChild = oElem.FirstChild; oChild != null;
            oChild = oChild.NextSibling)
            {
            if (oChild.LocalName.Equals(Tags.TAG_ISSUER))
            {
                // only accept the first XRIAuthority
                if (moIssuer == null)
                {
                    moIssuer = new NameID((XmlElement) oChild);
                }
            }
            else if (oChild.LocalName.Equals(Tags.TAG_SIGNATURE))
            {
                // only accept the first XRIAuthority
                if (moSignature == null)
                {
                    try
                    {
                        XmlDocument oDoc = new XmlDocument();
                        XmlElement oChildCopy =
                            (XmlElement) oDoc.ImportNode(oChild, true);
                        moSignature = new XMLSignature(oChildCopy, null);
                    }
                    catch (Exception oEx)
                    {
                        soLog.Warn(
                            "Caught exception while parsing Signature", oEx);
                    }
                }
            }
            else if (oChild.LocalName.Equals(Tags.TAG_SUBJECT))
            {
                // only accept the first XRIAuthority
                if (moSubject == null)
                {
                    moSubject = new Subject((XmlElement) oChild);
                }
            }
            else if (oChild.LocalName.Equals(Tags.TAG_CONDITIONS))
            {
                // only accept the first XRIAuthority
                if (moConditions == null)
                {
                    moConditions = new Conditions((XmlElement) oChild);
                }
            }
            else if (oChild.LocalName.Equals(Tags.TAG_ATTRIBUTESTATEMENT))
            {
                // only accept the first XRIAuthority
                if (moAttrStatement == null)
                {
                    moAttrStatement = new AttributeStatement((XmlElement) oChild);
                }
            }
            }
        }
예제 #4
0
파일: XRD.cs 프로젝트: AArnott/dotnetxri
        //throws XMLSecurityException
        /**
        * This will sign the XRD using the provided Private Key.  The
        * signature will be kept in DOM.  DOM will be created if it doesn't exist
        * already.
        * @param oKey - The private key to sign the descriptor with.
        * @throws XMLSecurityException
        */
        public void sign(PrivateKey oKey)
        {
            // build up the DOM (stored in moElem for future use)
            getDOM();

            // before signing, make sure that the document is properly normalized
            // this is separate from the XMLDSig canonicalization and is more for attributes, namespaces, etc.
            moElem.OwnerDocument.Normalize();

            XmlElement oAssertionElem =
                DOMUtils.getFirstChildElement(
                        moElem, Tags.NS_SAML, Tags.TAG_ASSERTION);
            if (oAssertionElem == null) {
                throw new XMLSecurityException(
                "Cannot create signature. No SAML Assertion attached to descriptor.");
            }

            XmlElement oSubjectElem =
                DOMUtils.getFirstChildElement(
                        oAssertionElem, Tags.NS_SAML, Tags.TAG_SUBJECT);
            if (oSubjectElem == null) {
                throw new XMLSecurityException(
                "Cannot create signature. SAML Assertion has no subject.");
            }

            // make sure the id attribute is present
            string sID = moElem.getAttributeNS(Tags.NS_XML, Tags.ATTR_ID_LOW);
            if ((sID == null) || (sID.Equals(""))) {
                throw new XMLSecurityException(
                        "Cannot create signature. ID is missing for " +
                        moElem.LocalName);
            }

            // Set the DOM so that it can be signed
            DOM3Utils.bestEffortSetIDAttr(moElem, Tags.NS_XML, Tags.ATTR_ID_LOW);

            // Build the empty signature.
            XmlDocument oDoc = moElem.getOwnerDocument();
            XMLSignature oSig =
                new XMLSignature(
                        oDoc, null, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
                        Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            // add all the transforms to the signature
            string[] oTransforms =
                new string[] { Transforms.TRANSFORM_ENVELOPED_SIGNATURE, Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS };
            Transforms oTrans = new Transforms(oSig.getDocument());
            for (int i = 0; i < oTransforms.Length; i++) {
                oTrans.addTransform(oTransforms[i]);
            }
            oSig.addDocument("#" + sID, oTrans);

            // now finally sign the thing
            oSig.sign(oKey);

            // now sub in this element
            XmlElement oSigElem = oSig.getElement();

            // insert the signature in the right place
            oAssertionElem.InsertBefore(oSigElem, oSubjectElem);
        }
예제 #5
0
파일: XRD.cs 프로젝트: AArnott/dotnetxri
        //throws XMLSecurityException
        /**
        * This will verify the XRD against the given public key.  DOM
        * must already be associated with this descriptor.
        * @param oPubKey
        * @throws XMLSecurityException
        */
        public void verifySignature(PublicKey oPubKey)
        {
            if (moElem == null) {
                throw new XMLSecurityException(
                "Cannot verify the signature. No DOM stored for XRD");
            }

            // make sure the ID attribute is present
            string sIDAttr = Tags.ATTR_ID_LOW;
            string sIDAttrNS = Tags.NS_XML;
            string sID = moElem.getAttributeNS(sIDAttrNS, sIDAttr);
            if ((sID == null) || (sID.Equals(""))) {
                throw new XMLSecurityException(
                        "Cannot verify the signature. ID is missing for " +
                        moElem.LocalName);
            }
            string sRef = "#" + sID;

            // Set the DOM so that it can be verified
            DOM3Utils.bestEffortSetIDAttr(moElem, sIDAttrNS, sIDAttr);

            XmlElement oAssertionElem =
                DOMUtils.getFirstChildElement(
                        moElem, Tags.NS_SAML, Tags.TAG_ASSERTION);

            if (oAssertionElem == null) {
                throw new XMLSecurityException(
                "Cannot verify the signature. No Assertion in XRD");
            }

            XmlElement oSigElem =
                DOMUtils.getFirstChildElement(
                        oAssertionElem, Tags.NS_XMLDSIG, Tags.TAG_SIGNATURE);

            if (oSigElem == null) {
                throw new XMLSecurityException(
                "Cannot verify the signature. No signature in Assertion");
            }

            // create the signature element to verify
            XMLSignature oSig = null;
            oSig = new XMLSignature(oSigElem, null);

            // Validate the signature content by checking the references
            string sFailedRef = null;
            SignedInfo oSignedInfo = oSig.getSignedInfo();
            if (oSignedInfo.getLength() != 1) {
                throw new XMLSecurityException(
                        "Cannot verify the signature. Expected 1 reference, got " +
                        oSignedInfo.getLength());
            }

            // make sure it references the correct element
            Reference oRef = oSignedInfo.item(0);
            string sURI = oRef.getURI();
            if (!sRef.Equals(sURI)) {
                throw new XMLSecurityException(
                "Cannot verify the signature. Reference Uri did not match ID");
            }

            // check that the transforms are ok
            bool bEnvelopedFound = false;
            Transforms oTransforms = oRef.getTransforms();
            for (int i = 0; i < oTransforms.getLength(); i++) {
                string sTransform = oTransforms.item(i).getURI();
                if (Transforms.TRANSFORM_ENVELOPED_SIGNATURE.Equals(sTransform)) {
                    // mark that we got the required transform
                    bEnvelopedFound = true;
                } else if (
                        !Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS.Equals(
                                sTransform)) {
                    // bonk if we don't have one of the two acceptable transforms
                    throw new XMLSecurityException(
                    "Unexpected transform in signature");
                }
            }

            if (!bEnvelopedFound) {
                throw new XMLSecurityException(
                        "Could not find expected " +
                        Transforms.TRANSFORM_ENVELOPED_SIGNATURE +
                " transform in signature");
            }

            // finally check the signature
            if (!oSig.checkSignatureValue(oPubKey)) {
                throw new RuntimeException("Signature failed to verify.");
            }
        }
예제 #6
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);
        }
예제 #7
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="signedXml">İmzası kontrol edilecek XML içeriği</param>
    /// <param name="unQaulifiedDigestAlgoritmList">Geçersiz signature.SignedInfo.SignatureMethod.Url
    /// <example>http://www.w3.org/2000/09/xmldsig#sha1</example></param>
    /// <param name="checkForEnvelopedSignature">Eğer true set edilirse İmzanın Enveloped yapısında olduğu kontrolü yapılır. Envelped yapısına olmayan İmzalarda Doğrulama sonucu başarısız döner.</param>
    /// <returns></returns>
    public static SignedDocumentValidationResult ValidateSignatureFromXml(string signedXml)
    {
        LicenseUtil.setLicenseXml(new MemoryStream(System.IO.File.ReadAllBytes(System.AppDomain.CurrentDomain.BaseDirectory + "/SignatureValidationConfig/Lisans/lisans.xml")));

        var context = new Context();

        context.Config = new tr.gov.tubitak.uekae.esya.api.xmlsignature.config.Config(System.AppDomain.CurrentDomain.BaseDirectory + "/SignatureValidationConfig/xmlsignature-config.xml");

        var file = System.IO.Path.GetTempFileName();

        System.IO.File.WriteAllText(file, signedXml);

        var sdvr      = new SignedDocumentValidationResult();
        var signature = XMLSignature.parse(new FileDocument(new FileInfo(file)), context);
        var result    = signature.verify();

        try
        {
            System.IO.File.Delete(file);
        }
        finally
        {
        }

        sdvr.Certificate = signature.SigningCertificate.asX509Certificate2();
        sdvr.CertificateValidationResult = new CertificateValidationResult();
        sdvr.SignatureInfo             = new SignatureInfo();
        sdvr.SignatureInfo.SigningTime = signature.SigningTime;
        sdvr.CertificateValidationResult.ValidationResultList = new List <SignatureValidator.DataTransferObject.ValidationResult>();

        //
        var nodeList = signature.Document.GetElementsByTagName("UBLVersionID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");

        if (nodeList != null && nodeList.Count > 0)
        {
            sdvr.SignatureInfo.UBLVersionID = nodeList.Item(0).InnerText;
        }

        if (context.ValidationResult != null && context.ValidationResult.getDetails() != null)
        {
            foreach (var item in context.ValidationResult.getDetails())
            {
                var vr = new SignatureValidator.DataTransferObject.ValidationResult();
                vr.Successful = item.isSuccessful();
                vr.Result     = vr.Successful ? tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.VALID.ToString() : tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.INVALID.ToString();
                vr.CheckText  = item.getCheckText();
                vr.ResultText = item.getResultText();
                sdvr.CertificateValidationResult.ValidationResultList.Add(vr);
            }
            sdvr.CertificateValidationResult.Successful = !sdvr.CertificateValidationResult.ValidationResultList.Exists(x => x.Successful.Equals(false));
        }

        sdvr.SignatureValidationResult                      = new SignatureValidator.DataTransferObject.SignatureValidationResult();
        sdvr.SignatureValidationResult.Successful           = result.getResultType() == tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.VALID;
        sdvr.SignatureValidationResult.ResultText           = result.getMessage() + Environment.NewLine + result.getResultType();
        sdvr.SignatureValidationResult.ValidationResultList = new List <SignatureValidator.DataTransferObject.ValidationResult>();

        foreach (var item in result.getDetails <tr.gov.tubitak.uekae.esya.api.xmlsignature.ValidationResult>())
        {
            var vr = new SignatureValidator.DataTransferObject.ValidationResult();

            vr.Successful = item.getResultType() == tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.VALID;
            vr.Result     = item.getResultType().ToString();
            vr.CheckText  = item.getCheckMessage();
            vr.ResultText = item.getCheckResult();

            sdvr.SignatureValidationResult.ValidationResultList.Add(vr);
        }
        return(sdvr);
    }