Package org.apache.xml.security.signature

Examples of org.apache.xml.security.signature.XMLSignature


                        WSSecurityException.FAILURE,
                        "invalidX509Data",
                        new Object[] { "for Signature - unkown public key Algo" });
            }
        }
        XMLSignature sig = null;
        try {
            sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
        } catch (XMLSecurityException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noXMLSig");
        }

        KeyInfo info = sig.getKeyInfo();
        String keyInfoUri = "KeyId-" + info.hashCode();
        info.setId(keyInfoUri);

        SecurityTokenReference secRef = new SecurityTokenReference(wssConfig,
                doc);
        String strUri = "STRId-" + secRef.hashCode();
        secRef.setID(strUri);

        String certUri = "CertId-" + certs[0].hashCode();

        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }

        if (parts == null) {
            parts = new Vector();
            WSEncryptionPart encP = new WSEncryptionPart(soapConstants
                    .getBodyQName().getLocalPart(), soapConstants
                    .getEnvelopeURI(), "Content");
            parts.add(encP);
        }

        /*
         * If the sender vouches, then we must sign the SAML token _and_ at
         * least one part of the message (usually the SOAP body). To do so we
         * need to
         * - put in a reference to the SAML token. Thus we create a STR
         *   and insert it into the wsse:Security header
         * - set a reference of the created STR to the signature and use STR
         *   Transfrom during the signature
         */
        Transforms transforms = null;
        SecurityTokenReference secRefSaml = null;

        try {
            if (senderVouches) {
                secRefSaml = new SecurityTokenReference(wssConfig, doc);
                String strSamlUri = "STRSAMLId-" + secRefSaml.hashCode();
                secRefSaml.setID(strSamlUri);
                // Decouple Refernce/KeyInfo setup - quick shot here
                Reference ref = new Reference(wssConfig, doc);
                ref.setURI("#" + assertion.getId());
                ref.setValueType(WSConstants.WSS_SAML_NS
                        + WSConstants.WSS_SAML_ASSERTION);
                secRefSaml.setReference(ref);
                // up to here
                Element ctx = createSTRParameter(doc);
                transforms = new Transforms(doc);
                transforms.addTransform(STRTransform.implementedTransformURI,
                        ctx);
                sig.addDocument("#" + strSamlUri, transforms);
            }
            for (int part = 0; part < parts.size(); part++) {
                WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part);
                String elemName = encPart.getName();
                String nmSpace = encPart.getNamespace();

                /*
                 * Set up the elements to sign. There are two resevered element
                 * names: "Token" and "STRTransform" "Token": Setup the
                 * Signature to either sign the information that points to the
                 * security token or the token itself. If its a direct
                 * reference sign the token, otherwise sign the KeyInfo
                 * Element. "STRTransform": Setup the ds:Reference to use STR
                 * Transform
                 *
                 */
                if (elemName.equals("Token")) {
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    if (keyIdentifierType == WSConstants.BST_DIRECT_REFERENCE) {
                        sig.addDocument("#" + certUri, transforms);
                    } else {
                        sig.addDocument("#" + keyInfoUri, transforms);
                    }
                } else if (elemName.equals("STRTransform")) { // STRTransform
                    Element ctx = createSTRParameter(doc);
                    transforms = new Transforms(doc);
                    transforms.addTransform(
                            STRTransform.implementedTransformURI, ctx);
                    sig.addDocument("#" + strUri, transforms);
                } else {
                    Element body = (Element) WSSecurityUtil.findElement(
                            envelope, elemName, nmSpace);
                    if (body == null) {
                        throw new WSSecurityException(
                                WSSecurityException.FAILURE, "noEncElement",
                                new Object[] { nmSpace + ", " + elemName });
                    }
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    sig.addDocument("#" + setWsuId(body), transforms);
                }
            }
        } catch (TransformationException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noXMLSig", null, e1);
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noXMLSig", null, e1);
        }

        sig.addResourceResolver(EnvelopeIdResolver.getInstance(wssConfig));

        /*
         * The order to prepend is:
         * - signature
         * - BinarySecurityToken (depends on mode)
         * - SecurityTokenRefrence (depends on mode)
         * - SAML token
         */

        WSSecurityUtil.prependChildElement(doc, securityHeader, sig
                .getElement(), false);

        if (tlog.isDebugEnabled()) {
            t2 = System.currentTimeMillis();
        }
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(wssConfig, doc);
            if (senderVouches) {
                ref.setURI("#" + certUri);
                BinarySecurity bstToken = null;
                bstToken = new X509Security(wssConfig, doc);
                ((X509Security) bstToken).setX509Certificate(certs[0]);
                bstToken.setID(certUri);
                WSSecurityUtil.prependChildElement(doc, securityHeader,
                        bstToken.getElement(), false);
                wsDocInfo.setBst(bstToken.getElement());
                ref.setValueType(bstToken.getValueType());
            } else {
                ref.setURI("#" + assertion.getId());
                ref.setValueType(WSConstants.WSS_SAML_NS
                        + WSConstants.WSS_SAML_ASSERTION);
            }
            secRef.setReference(ref);
            break;
        //
        //            case WSConstants.ISSUER_SERIAL :
        //                XMLX509IssuerSerial data =
        //                    new XMLX509IssuerSerial(doc, certs[0]);
        //                secRef.setX509IssuerSerial(data);
        //                break;
        //
        //            case WSConstants.X509_KEY_IDENTIFIER :
        //                secRef.setKeyIdentifier(certs[0]);
        //                break;
        //
        //            case WSConstants.SKI_KEY_IDENTIFIER :
        //                secRef.setKeyIdentifierSKI(certs[0], crypto);
        //                break;
        //
        default:
            throw new WSSecurityException(WSSecurityException.FAILURE,
                    "unsupportedKeyId");
        }

        if (tlog.isDebugEnabled()) {
            t3 = System.currentTimeMillis();
        }
        info.addUnknownElement(secRef.getElement());

        Element samlToken = null;
        try {
            samlToken = (Element) assertion.toDOM(doc);
        } catch (SAMLException e2) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noSAMLdoc", null, e2);
        }
        if (senderVouches) {
            WSSecurityUtil.prependChildElement(doc, securityHeader, secRefSaml
                    .getElement(), true);
        }

        wsDocInfo.setAssertion(samlToken);
        WSSecurityUtil
                .prependChildElement(doc, securityHeader, samlToken, true);

        WSDocInfoStore.store(wsDocInfo);
        try {
            if (senderVouches) {
                sig
                        .sign(issuerCrypto.getPrivateKey(issuerKeyName,
                                issuerKeyPW));
            } else {
                sig.sign(userCrypto.getPrivateKey(user, password));
            }
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    null, null, e1);
        } catch (Exception e1) {
View Full Code Here


    private ConvEngineResult VerifySignature(
        Element elem,
        DerivedKeyCallbackHandler dkcbHandler)
        throws ConversationException {
        ConvEngineResult convResult = null;
        XMLSignature sig = null;
//      System.out.println("******** at VerifySignature");
//    ByteArrayOutputStream os = new ByteArrayOutputStream();
//    XMLUtils.outputDOM(elem, os, true);
//    String osStr = os.toString();
//    System.out.println(osStr);
        try {
            sig = new XMLSignature(elem, null);
        } catch (XMLSignatureException e2) {
            throw new ConversationException("noXMLSig");
        } catch (XMLSecurityException e2) {
            throw new ConversationException("noXMLSig");
        }
        String sigMethodURI = sig.getSignedInfo().getSignatureMethodURI();
        //verifying the sinature
        if (sigMethodURI.equals(XMLSignature.ALGO_ID_MAC_HMAC_SHA1)) {

            try {
                //sign.verifiyXMLHMac_SHA1_Signarue(sig, dkcbHandler);
View Full Code Here

                WSSecurityUtil.findWsseSecurityHeaderBlock(WSSConfig.getDefaultWSConfig(),
                        doc,
                        doc.getDocumentElement(),
                        true);

        XMLSignature sig = null;
        try {
            sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
        } catch (XMLSecurityException e) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noXMLSig");
        }

        KeyInfo info = sig.getKeyInfo();
        String keyInfoUri = "KeyId-" + info.hashCode();
        info.setId(keyInfoUri);

        SecurityTokenReference secRef = new SecurityTokenReference(WSSConfig.getDefaultWSConfig(), doc);
        String strUri = "STRId-" + secRef.hashCode();
        secRef.setID(strUri);

        if (parts == null) {
            parts = new Vector();
            WSEncryptionPart encP =
                    new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                            soapConstants.getEnvelopeURI(),
                            "Content");
            parts.add(encP);
        }

        /*
         * The below "for" loop (which perform transforms) is
         * copied from
         *        build(Document doc, Crypto crypto) method in
         *            org.apache.ws.security.message.WSEncryptBody.java                 
         */

        Transforms transforms = null;

        for (int part = 0; part < parts.size(); part++) {
            WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part);
            String elemName = encPart.getName();
            String nmSpace = encPart.getNamespace();

            /*
             * Set up the elements to sign. There are two resevered element
             * names: "Token" and "STRTransform" "Token": Setup the Signature
             * to either sign the information that points to the security token
             * or the token itself. If its a direct reference sign the token,
             * otherwise sign the KeyInfo Element. "STRTransform": Setup the
             * ds:Reference to use STR Transform
             *
             */
            try {
                if (elemName.equals("Token")) {
                    transforms = new Transforms(doc);
                    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    sig.addDocument("#" + keyInfoUri, transforms);
                } else if (elemName.equals("STRTransform")) { // STRTransform
                    Element ctx = createSTRParameter(doc);
                    transforms = new Transforms(doc);
                    transforms.addTransform(STRTransform.implementedTransformURI,
                            ctx);
                    sig.addDocument("#" + strUri, transforms);
                } else {
                    Element body =
                            (Element) WSSecurityUtil.findElement(envelope,
                                    elemName,
                                    nmSpace);
                    if (body == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE,
                                "noEncElement",
                                new Object[]{nmSpace + ", " + elemName});
                    }
                    transforms = new Transforms(doc);
                    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    sig.addDocument("#" + setWsuId(body), transforms);
                }
            } catch (TransformationException e1) {
                throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                        "noXMLSig",
                        null,
                        e1);
            } catch (XMLSignatureException e1) {
                throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                        "noXMLSig",
                        null,
                        e1);
            }
        }

        sig.addResourceResolver(EnvelopeIdResolver.getInstance(WSSConfig.getDefaultWSConfig()));

        /*
         * Prepending order
         * -Append the signature element.
         * -Apped the KeyInfo element
         */
        WSSecurityUtil.appendChildElement(doc,
                securityHeader,
                sig.getElement());

        /*
         * Put the "Reference object" into secRef in KeyInfo
         */
        secRef.setReference(ref);

        info.addUnknownElement(secRef.getElement());

        try {
            sig.sign(sharedKey);
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    null,
                    null,
                    e1);
View Full Code Here

            if (signatureElem == null) {
                System.out.println("The document is not signed");
                return;
            }

            XMLSignature sig = new XMLSignature(signatureElem, BaseURI);

            boolean verify = sig.checkSignatureValue(sig.getKeyInfo().getPublicKey());
            System.out.println("Server verification complete.");

            System.out.println("The signature is" + (verify
                    ? " "
                    : " not ") + "valid");
View Full Code Here

                    privateKeyPass.toCharArray());

            Element soapHeaderElement = (Element) ((Element) doc.getFirstChild()).getElementsByTagNameNS("*", "Header").item(0);
            Element soapSignatureElement = (Element) soapHeaderElement.getElementsByTagNameNS("*", "Signature").item(0);

            XMLSignature sig = new XMLSignature(doc, baseURI,
                    XMLSignature.ALGO_ID_SIGNATURE_DSA);

            soapSignatureElement.appendChild(sig.getElement());
            sig.addDocument("#Body");


            X509Certificate cert =
                    (X509Certificate) ks.getCertificate(certificateAlias);


            sig.addKeyInfo(cert);
            sig.addKeyInfo(cert.getPublicKey());
            sig.sign(privateKey);

            Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
            byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);

            InputSource is = new InputSource(new java.io.ByteArrayInputStream(canonicalMessage));
View Full Code Here

        final X509Certificate signerCert = (X509Certificate) xKMScertificatechain.get(0);
        final XKMSCAServiceRequest xKMSServiceReq = (XKMSCAServiceRequest)request;
        final Document doc = xKMSServiceReq.getDoc();
        if (xKMSServiceReq.isSign()) {
          try {
        XMLSignature xmlSig = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        Transforms transforms = new Transforms(doc);
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
        xmlSig.addDocument("#" + xKMSServiceReq.getId(), transforms, Constants.ALGO_ID_DIGEST_SHA1);             
        xmlSig.addKeyInfo(signerCert);
        doc.getDocumentElement().insertBefore(xmlSig.getElement() ,doc.getDocumentElement().getFirstChild());
        xmlSig.sign(xKMSkey);
            returnval = new XKMSCAServiceResponse(doc);
          } catch (XMLSignatureException e) {
            throw new ExtendedCAServiceRequestException(e);
      } catch (XMLSecurityException e) {
        throw new ExtendedCAServiceRequestException(e);
View Full Code Here

                        }
                    );
                }
            }
        }
        XMLSignature sig = null;

        if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
            Element canonElem = XMLUtils.createElementInSignatureSpace(doc,
                    Constants._TAG_CANONICALIZATIONMETHOD);

            canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo);

            if (wssConfig.isWsiBSPCompliant()) {
                Set prefixes = getInclusivePrefixes(securityHeader, false);

                InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(
                        doc, prefixes);

                canonElem.appendChild(inclusiveNamespaces.getElement());
            }

            try {
                SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(
                        doc, sigAlgo);
                sig = new XMLSignature(doc, null, signatureAlgorithm
                        .getElement(), canonElem);
            } catch (XMLSecurityException e) {
                log.error("", e);
                throw new WSSecurityException(
                    WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e
                );
            }
        } else {
            try {
                sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
            } catch (XMLSecurityException e) {
                log.error("", e);
                throw new WSSecurityException(
                    WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e
                );
            }
        }
        /*
         * If we don't generate a new Transforms for each addDocument here, then
         * only the last Transforms is put into the according ds:Reference
         * element, i.e. the first ds:Reference does not contain a Transforms
         * element. Thus the verification fails (somehow)
         */

        KeyInfo info = sig.getKeyInfo();
        String keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", info);
        info.setId(keyInfoUri);

        SecurityTokenReference secRef = new SecurityTokenReference(doc);
        String secRefId = wssConfig.getIdAllocator().createSecureId("STRId-", info);
        secRef.setID(secRefId);

        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }

        if (parts == null) {
            parts = new Vector();
            WSEncryptionPart encP = new WSEncryptionPart(soapConstants
                    .getBodyQName().getLocalPart(), soapConstants
                    .getEnvelopeURI(), "Content");
            parts.add(encP);
        }

        Transforms transforms = null;

        for (int part = 0; part < parts.size(); part++) {
            WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part);

            String idToSign = encPart.getId();

            String elemName = encPart.getName();
            String nmSpace = encPart.getNamespace();

            /*
             * Set up the elements to sign. There are two reserved element
             * names: "Token" and "STRTransform" "Token": Setup the Signature to
             * either sign the information that points to the security token or
             * the token itself. If its a direct reference sign the token,
             * otherwise sign the KeyInfo Element. "STRTransform": Setup the
             * ds:Reference to use STR Transform
             *
             */
            try {
                if (idToSign != null) {
                    Element toSignById = WSSecurityUtil
                            .findElementById(doc.getDocumentElement(),
                                    idToSign, WSConstants.WSU_NS);
                    if (toSignById == null) {
                        toSignById = WSSecurityUtil.findElementById(doc
                                .getDocumentElement(), idToSign, null);
                    }
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    if (wssConfig.isWsiBSPCompliant()) {
                        transforms.item(0).getElement().appendChild(
                                new InclusiveNamespaces(doc,
                                        getInclusivePrefixes(toSignById))
                                        .getElement());
                    }
                    sig.addDocument("#" + idToSign, transforms);
                }
                else if (elemName.equals("Token")) {
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    if (keyIdentifierType == WSConstants.BST_DIRECT_REFERENCE) {
                        if (wssConfig.isWsiBSPCompliant()) {
                            transforms
                                    .item(0)
                                    .getElement()
                                    .appendChild(
                                            new InclusiveNamespaces(
                                                    doc,
                                                    getInclusivePrefixes(securityHeader))
                                                    .getElement());
                        }
                        sig.addDocument("#" + certUri, transforms);
                    } else {
                        if (wssConfig.isWsiBSPCompliant()) {
                            transforms.item(0).getElement().appendChild(
                                    new InclusiveNamespaces(doc,
                                            getInclusivePrefixes(info
                                                    .getElement()))
                                            .getElement());
                        }
                        sig.addDocument("#" + keyInfoUri, transforms);
                    }
                } else if (elemName.equals("STRTransform")) { // STRTransform
                    Element ctx = createSTRParameter(doc);
                    transforms = new Transforms(doc);
                    transforms.addTransform(
                            STRTransform.implementedTransformURI, ctx);
                    sig.addDocument("#" + secRefId, transforms);
                } else if (elemName.equals("Assertion")) { // Assertion

                    String id = null;
                    id = SAMLUtil.getAssertionId(envelope, elemName, nmSpace);

                    Element body = (Element) WSSecurityUtil.findElement(
                            envelope, elemName, nmSpace);
                    if (body == null) {
                        throw new WSSecurityException(
                                WSSecurityException.FAILURE, "noEncElement",
                                new Object[] { nmSpace + ", " + elemName });
                    }
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    if (wssConfig.isWsiBSPCompliant()) {
                        transforms.item(0).getElement().appendChild(
                                new InclusiveNamespaces(doc,
                                        getInclusivePrefixes(body))
                                        .getElement());
                    }
                    String prefix = WSSecurityUtil.setNamespace(body,
                            WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
                    body.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id",
                            id);
                    sig.addDocument("#" + id, transforms);

                } else {
                    Element body = (Element) WSSecurityUtil.findElement(
                            envelope, elemName, nmSpace);
                    if (body == null) {
                        throw new WSSecurityException(
                                WSSecurityException.FAILURE, "noEncElement",
                                new Object[] { nmSpace + ", " + elemName });
                    }
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    if (wssConfig.isWsiBSPCompliant()) {
                        transforms.item(0).getElement().appendChild(
                                new InclusiveNamespaces(doc,
                                        getInclusivePrefixes(body))
                                        .getElement());
                    }
                    sig.addDocument("#" + setWsuId(body), transforms);
                }
            } catch (TransformationException e1) {
                throw new WSSecurityException(
                        WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null,
                        e1);
            } catch (XMLSignatureException e1) {
                throw new WSSecurityException(
                        WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null,
                        e1);
            }
        }

        sig.addResourceResolver(EnvelopeIdResolver.getInstance());

        WSSecurityUtil.prependChildElement(securityHeader, sig.getElement());
        if (tlog.isDebugEnabled()) {
            t2 = System.currentTimeMillis();
        }

        byte[] secretKey = null;
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(doc);
            ref.setURI("#" + certUri);
            BinarySecurity bstToken = null;
            if (!useSingleCert) {
                bstToken = new PKIPathSecurity(doc);
                ((PKIPathSecurity) bstToken).setX509Certificates(certs, false,
                        crypto);
            } else {
                bstToken = new X509Security(doc);
                ((X509Security) bstToken).setX509Certificate(certs[0]);
            }
            ref.setValueType(bstToken.getValueType());
            secRef.setReference(ref);
            bstToken.setID(certUri);
            WSSecurityUtil.prependChildElement(securityHeader, bstToken.getElement());
            wsDocInfo.setBst(bstToken.getElement());
            break;

        case WSConstants.ISSUER_SERIAL:
            XMLX509IssuerSerial data = new XMLX509IssuerSerial(doc, certs[0]);
            X509Data x509Data = new X509Data(doc);
            x509Data.add(data);
            secRef.setX509IssuerSerial(x509Data);
            break;

        case WSConstants.X509_KEY_IDENTIFIER:
            secRef.setKeyIdentifier(certs[0]);
            break;

        case WSConstants.SKI_KEY_IDENTIFIER:
            secRef.setKeyIdentifierSKI(certs[0], crypto);
            break;

        case WSConstants.UT_SIGNING:
            Reference refUt = new Reference(doc);
            refUt.setValueType(WSConstants.USERNAMETOKEN_NS + "#UsernameToken");
            String utId = usernameToken.getId();
            if (utId == null) {
                utId = wssConfig.getIdAllocator().createId("usernameTokenId-", usernameToken);
                usernameToken.setId(utId);
            }
            refUt.setURI("#" + utId);
            secRef.setReference(refUt);
            secretKey = usernameToken.getSecretKey();
            break;

        case WSConstants.THUMBPRINT_IDENTIFIER:
            secRef.setKeyIdentifierThumb(certs[0]);
            break;

        default:
            throw new WSSecurityException(WSSecurityException.FAILURE,
                    "unsupportedKeyId");
        }
        if (tlog.isDebugEnabled()) {
            t3 = System.currentTimeMillis();
        }
        info.addUnknownElement(secRef.getElement());

        boolean remove = WSDocInfoStore.store(wsDocInfo);
        try {
            if (keyIdentifierType == WSConstants.UT_SIGNING) {
                sig.sign(sig.createSecretKey(secretKey));
            } else {
                sig.sign(crypto.getPrivateKey(user, password));
            }
            signatureValue = sig.getSignatureValue();
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    null, null, e1);
        } catch (Exception e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
View Full Code Here

                        pubKeyAlgo
                    }
                );
            }
        }
        XMLSignature sig = null;
        try {
            sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
        } catch (XMLSecurityException e) {
            throw new WSSecurityException(
                WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e
            );
        }

        KeyInfo info = sig.getKeyInfo();
        String keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", info);
        info.setId(keyInfoUri);

        SecurityTokenReference secRef = new SecurityTokenReference(doc);
        String strUri = wssConfig.getIdAllocator().createSecureId("STRId-", secRef);
        secRef.setID(strUri);

        String certUri = wssConfig.getIdAllocator().createSecureId("CertId-", certs[0]);

        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }

        if (parts == null) {
            parts = new Vector();
            WSEncryptionPart encP = new WSEncryptionPart(soapConstants
                    .getBodyQName().getLocalPart(), soapConstants
                    .getEnvelopeURI(), "Content");
            parts.add(encP);
        }

        /*
         * If the sender vouches, then we must sign the SAML token _and_ at
         * least one part of the message (usually the SOAP body). To do so we
         * need to - put in a reference to the SAML token. Thus we create a STR
         * and insert it into the wsse:Security header - set a reference of the
         * created STR to the signature and use STR Transfrom during the
         * signature
         */
        Transforms transforms = null;
        SecurityTokenReference secRefSaml = null;

        try {
            if (senderVouches) {
                secRefSaml = new SecurityTokenReference(doc);
                String strSamlUri = wssConfig.getIdAllocator().createSecureId("STRSAMLId-", secRefSaml);
                secRefSaml.setID(strSamlUri);
                // Decouple Refernce/KeyInfo setup - quick shot here
                Reference ref = new Reference(doc);
                ref.setURI("#" + assertion.getId());
                ref.setValueType(WSConstants.WSS_SAML_NS
                        + WSConstants.WSS_SAML_ASSERTION);
                secRefSaml.setReference(ref);
                // up to here
                Element ctx = createSTRParameter(doc);
                transforms = new Transforms(doc);
                transforms.addTransform(STRTransform.implementedTransformURI,
                        ctx);
                sig.addDocument("#" + strSamlUri, transforms);
            }
            for (int part = 0; part < parts.size(); part++) {
                WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part);
                String elemName = encPart.getName();
                String nmSpace = encPart.getNamespace();

                /*
                 * Set up the elements to sign. There are two resevered element
                 * names: "Token" and "STRTransform" "Token": Setup the
                 * Signature to either sign the information that points to the
                 * security token or the token itself. If its a direct reference
                 * sign the token, otherwise sign the KeyInfo Element.
                 * "STRTransform": Setup the ds:Reference to use STR Transform
                 *
                 */
                if (elemName.equals("Token")) {
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    if (keyIdentifierType == WSConstants.BST_DIRECT_REFERENCE) {
                        sig.addDocument("#" + certUri, transforms);
                    } else {
                        sig.addDocument("#" + keyInfoUri, transforms);
                    }
                } else if (elemName.equals("STRTransform")) { // STRTransform
                    Element ctx = createSTRParameter(doc);
                    transforms = new Transforms(doc);
                    transforms.addTransform(
                            STRTransform.implementedTransformURI, ctx);
                    sig.addDocument("#" + strUri, transforms);
                } else {
                    Element body = (Element) WSSecurityUtil.findElement(
                            envelope, elemName, nmSpace);
                    if (body == null) {
                        throw new WSSecurityException(
                                WSSecurityException.FAILURE, "noEncElement",
                                new Object[] { nmSpace + ", " + elemName });
                    }
                    transforms = new Transforms(doc);
                    transforms
                            .addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                    sig.addDocument("#" + setWsuId(body), transforms);
                }
            }
        } catch (TransformationException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noXMLSig", null, e1);
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noXMLSig", null, e1);
        }

        sig.addResourceResolver(EnvelopeIdResolver.getInstance());

        /*
         * The order to prepend is: - signature - BinarySecurityToken (depends
         * on mode) - SecurityTokenRefrence (depends on mode) - SAML token
         */

        WSSecurityUtil.prependChildElement(securityHeader, sig.getElement());

        if (tlog.isDebugEnabled()) {
            t2 = System.currentTimeMillis();
        }
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(doc);
            if (senderVouches) {
                ref.setURI("#" + certUri);
                BinarySecurity bstToken = null;
                bstToken = new X509Security(doc);
                ((X509Security) bstToken).setX509Certificate(certs[0]);
                bstToken.setID(certUri);
                WSSecurityUtil.prependChildElement(securityHeader, bstToken.getElement());
                wsDocInfo.setBst(bstToken.getElement());
                ref.setValueType(bstToken.getValueType());
            } else {
                ref.setURI("#" + assertion.getId());
                ref.setValueType(WSConstants.WSS_SAML_NS
                        + WSConstants.WSS_SAML_ASSERTION);
            }
            secRef.setReference(ref);
            break;
        //
        // case WSConstants.ISSUER_SERIAL :
        // XMLX509IssuerSerial data =
        // new XMLX509IssuerSerial(doc, certs[0]);
        // secRef.setX509IssuerSerial(data);
        // break;
        //
        // case WSConstants.X509_KEY_IDENTIFIER :
        // secRef.setKeyIdentifier(certs[0]);
        // break;
        //
        // case WSConstants.SKI_KEY_IDENTIFIER :
        // secRef.setKeyIdentifierSKI(certs[0], crypto);
        // break;
        //
        default:
            throw new WSSecurityException(WSSecurityException.FAILURE,
                    "unsupportedKeyId");
        }

        if (tlog.isDebugEnabled()) {
            t3 = System.currentTimeMillis();
        }
        info.addUnknownElement(secRef.getElement());
       
        Element keyInfoElement = info.getElement();
        keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
                + WSConstants.SIG_PREFIX, WSConstants.SIG_NS);

        Element samlToken = null;
        try {
            samlToken = (Element) assertion.toDOM(doc);
        } catch (SAMLException e2) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    "noSAMLdoc", null, e2);
        }
        if (senderVouches) {
            WSSecurityUtil.prependChildElement(securityHeader, secRefSaml.getElement());
        }

        wsDocInfo.setAssertion(samlToken);
        WSSecurityUtil.prependChildElement(securityHeader, samlToken);

        boolean remove = WSDocInfoStore.store(wsDocInfo);
        try {
            if (senderVouches) {
                sig
                        .sign(issuerCrypto.getPrivateKey(issuerKeyName,
                                issuerKeyPW));
            } else {
                sig.sign(userCrypto.getPrivateKey(user, password));
            }
            signatureValue = sig.getSignatureValue();
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
                    null, null, e1);
        } catch (Exception e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE,
View Full Code Here

        long t0 = 0, t1 = 0, t2 = 0;
        if (tlog.isDebugEnabled()) {
            t0 = System.currentTimeMillis();
        }

        XMLSignature sig = null;
        try {
            sig = new XMLSignature(elem, null);
        } catch (XMLSecurityException e2) {
            throw new WSSecurityException(
                WSSecurityException.FAILED_CHECK, "noXMLSig", null, e2
            );
        }

        sig.addResourceResolver(EnvelopeIdResolver.getInstance());

        KeyInfo info = sig.getKeyInfo();
        byte[] secretKey = null;
        UsernameToken ut = null;
        DerivedKeyToken dkt = null;
        SAMLKeyInfo samlKi = null;
        String customTokenId = null;
        java.security.PublicKey publicKey = null;
        X509Certificate[] certs = null;
        boolean validateCertificateChain = false;
       
        if (info != null && info.containsKeyValue()) {
            try {
                publicKey = info.getPublicKey();
            } catch (Exception ex) {
                throw new WSSecurityException(ex.getMessage(), ex);
            }
        } else if (info != null) {
            Node node =
                WSSecurityUtil.getDirectChild(
                    info.getElement(),
                    SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
                    WSConstants.WSSE_NS
                );
            if (node == null) {
                throw new WSSecurityException(
                    WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
                );
            }
            SecurityTokenReference secRef = new SecurityTokenReference((Element) node);
            //
            // Here we get some information about the document that is being
            // processed, in particular the crypto implementation, and already
            // detected BST that may be used later during dereferencing.
            //
            if (secRef.containsReference()) {
                org.apache.ws.security.message.token.Reference ref = secRef.getReference();
               
                String uri = ref.getURI();
                if (uri.charAt(0) == '#') {
                    uri = uri.substring(1);
                }
                Processor processor = wsDocInfo.getProcessor(uri);
                if (processor == null) {
                    Element token = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                    //
                    // at this point check token type: Binary, SAML, EncryptedKey, Custom
                    //
                    QName el = new QName(token.getNamespaceURI(), token.getLocalName());
                    if (el.equals(WSSecurityEngine.binaryToken)) {
                        certs = getCertificatesTokenReference(token, crypto);
                        if (certs != null && certs.length > 1) {
                            validateCertificateChain = true;
                        }
                    } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
                        if (crypto == null) {
                            throw new WSSecurityException(
                                    WSSecurityException.FAILURE, "noSigCryptoFile"
                            );
                        }
                        samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                        certs = samlKi.getCerts();
                        secretKey = samlKi.getSecret();

                    } else if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)){
                        if (crypto == null) {
                            throw new WSSecurityException(
                                WSSecurityException.FAILURE, "noSigCryptoFile"
                            );
                        }
                        EncryptedKeyProcessor encryptKeyProcessor = new EncryptedKeyProcessor();
                        encryptKeyProcessor.handleEncryptedKey(token, cb, crypto);
                        secretKey = encryptKeyProcessor.getDecryptedBytes();
                    } else {
                        // Try custom token through callback handler
                        // try to find a custom token
                        String id = secRef.getReference().getURI();
                        if (id.charAt(0) == '#') {
                            id = id.substring(1);
                        }
                        WSPasswordCallback pwcb =
                            new WSPasswordCallback(id, WSPasswordCallback.CUSTOM_TOKEN);
                        try {
                            Callback[] callbacks = new Callback[]{pwcb};
                            cb.handle(callbacks);
                        } catch (Exception e) {
                            throw new WSSecurityException(
                                    WSSecurityException.FAILURE,
                                    "noPassword",
                                    new Object[] {id},
                                    e
                            );
                        }

                        secretKey = pwcb.getKey();
                        customTokenId = id;
                        if (secretKey == null) {
                            throw new WSSecurityException(
                                    WSSecurityException.INVALID_SECURITY,
                                    "unsupportedKeyInfo",
                                    new Object[]{el.toString()}
                            );
                        }
                    }
                } else if (processor instanceof UsernameTokenProcessor) {
                    ut = ((UsernameTokenProcessor)processor).getUt();
                    if (ut.isDerivedKey()) {
                        secretKey = ut.getDerivedKey();
                    } else {
                        secretKey = ut.getSecretKey(secretKeyLength);
                    }
                } else if (processor instanceof BinarySecurityTokenProcessor) {
                    certs = ((BinarySecurityTokenProcessor)processor).getCertificates();
                    if (certs != null && certs.length > 1) {
                        validateCertificateChain = true;
                    }
                } else if (processor instanceof EncryptedKeyProcessor) {
                    EncryptedKeyProcessor ekProcessor = (EncryptedKeyProcessor)processor;
                    secretKey = ekProcessor.getDecryptedBytes();
                    customTokenId = ekProcessor.getId();
                } else if (processor instanceof SecurityContextTokenProcessor) {
                    SecurityContextTokenProcessor sctProcessor =
                        (SecurityContextTokenProcessor)processor;
                    secretKey = sctProcessor.getSecret();
                    customTokenId = sctProcessor.getIdentifier();
                } else if (processor instanceof DerivedKeyTokenProcessor) {
                    DerivedKeyTokenProcessor dktProcessor =
                        (DerivedKeyTokenProcessor) processor;
                    String signatureMethodURI = sig.getSignedInfo().getSignatureMethodURI();
                    dkt = dktProcessor.getDerivedKeyToken();
                    int keyLength = (dkt.getLength() > 0) ? dkt.getLength() :
                        WSSecurityUtil.getKeyLength(signatureMethodURI);
                   
                    secretKey = dktProcessor.getKeyBytes(keyLength);
                } else if (processor instanceof SAMLTokenProcessor) {
                    if (crypto == null) {
                        throw new WSSecurityException(
                            WSSecurityException.FAILURE, "noSigCryptoFile"
                        );
                    }
                    SAMLTokenProcessor samlp = (SAMLTokenProcessor) processor;
                    samlKi = SAMLUtil.getSAMLKeyInfo(samlp.getSamlTokenElement(), crypto, cb);
                    certs = samlKi.getCerts();
                    secretKey = samlKi.getSecret();
                    publicKey = samlKi.getPublicKey();
                }
            } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
                certs = secRef.getX509IssuerSerial(crypto);
            } else if (secRef.containsKeyIdentifier()) {
                if (secRef.getKeyIdentifierValueType().equals(SecurityTokenReference.ENC_KEY_SHA1_URI)) {
                    String id = secRef.getKeyIdentifierValue();
                    WSPasswordCallback pwcb =
                        new WSPasswordCallback(
                            id,
                            null,
                            SecurityTokenReference.ENC_KEY_SHA1_URI,
                            WSPasswordCallback.ENCRYPTED_KEY_TOKEN
                        );
                    try {
                        Callback[] callbacks = new Callback[]{pwcb};
                        cb.handle(callbacks);
                    } catch (Exception e) {
                        throw new WSSecurityException(
                            WSSecurityException.FAILURE,
                            "noPassword",
                            new Object[] {id},
                            e
                        );
                    }
                    secretKey = pwcb.getKey();
                } else if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) {
                    Element token =
                        secRef.getKeyIdentifierTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                   
                    if (crypto == null) {
                        throw new WSSecurityException(
                            WSSecurityException.FAILURE, "noSigCryptoFile"
                        );
                    }
                    samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                    certs = samlKi.getCerts();
                    secretKey = samlKi.getSecret();
                    publicKey = samlKi.getPublicKey();
                } else {
                    certs = secRef.getKeyIdentifier(crypto);
                }
            } else {
                throw new WSSecurityException(
                    WSSecurityException.INVALID_SECURITY,
                    "unsupportedKeyInfo",
                    new Object[]{node.toString()}
                );
            }
        } else {
            if (crypto == null) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
            }
            if (crypto.getDefaultX509Alias() != null) {
                certs = crypto.getCertificates(crypto.getDefaultX509Alias());
            } else {
                throw new WSSecurityException(
                    WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
                );
            }
        }
        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }
        if ((certs == null || certs.length == 0 || certs[0] == null)
            && secretKey == null
            && publicKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
        }
        if (certs != null) {
            try {
                for (int i = 0; i < certs.length; i++) {
                    certs[i].checkValidity();
                }
            } catch (CertificateExpiredException e) {
                throw new WSSecurityException(
                    WSSecurityException.FAILED_CHECK, "invalidCert", null, e
                );
            } catch (CertificateNotYetValidException e) {
                throw new WSSecurityException(
                    WSSecurityException.FAILED_CHECK, "invalidCert", null, e
                );
            }
        }
        //
        // Delegate verification of a public key to a Callback Handler
        //
        if (publicKey != null) {
            PublicKeyCallback pwcb =
                new PublicKeyCallback(publicKey);
            try {
                Callback[] callbacks = new Callback[]{pwcb};
                cb.handle(callbacks);
                if (!pwcb.isVerified()) {
                    throw new WSSecurityException(
                        WSSecurityException.FAILED_AUTHENTICATION, null, null, null
                    );
                }
            } catch (Exception e) {
                throw new WSSecurityException(
                    WSSecurityException.FAILED_AUTHENTICATION, null, null, e
                );
            }
        }
        try {
            boolean signatureOk = false;
            if (certs != null) {
                signatureOk = sig.checkSignatureValue(certs[0]);
            } else if (publicKey != null) {
                signatureOk = sig.checkSignatureValue(publicKey);
            } else {
                signatureOk = sig.checkSignatureValue(sig.createSecretKey(secretKey));
            }
            if (signatureOk) {
                if (tlog.isDebugEnabled()) {
                    t2 = System.currentTimeMillis();
                    tlog.debug(
                        "Verify: total= " + (t2 - t0) + ", prepare-cert= " + (t1 - t0)
                        + ", verify= " + (t2 - t1)
                    );
                }
                signatureValue[0] = sig.getSignatureValue();
                //
                // Now dig into the Signature element to get the elements that
                // this Signature covers. Build the QName of these Elements and
                // return them to caller
                //
                SignedInfo si = sig.getSignedInfo();
                int numReferences = si.getLength();
                for (int i = 0; i < numReferences; i++) {
                    Reference siRef;
                    try {
                        siRef = si.item(i);
View Full Code Here

                canonElem.appendChild(inclusiveNamespaces.getElement());
            }

            try {
                SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo);
                sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);
            } catch (XMLSecurityException e) {
                log.error("", e);
                throw new WSSecurityException(
                    WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e
                );
            }
        } else {
            try {
                sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
            } catch (XMLSecurityException e) {
                log.error("", e);
                throw new WSSecurityException(
                    WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e
                );
View Full Code Here

TOP

Related Classes of org.apache.xml.security.signature.XMLSignature

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.