Search in sources :

Example 61 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project cxf by apache.

the class MetadataTest method testGetMetadata.

@org.junit.Test
public void testGetMetadata() throws Exception {
    URL busFile = MetadataTest.class.getResource("client.xml");
    String address = "https://localhost:" + PORT + "/sso/metadata";
    WebClient client = WebClient.create(address, busFile.toString());
    client.accept("text/xml");
    Response response = client.get();
    assertEquals(response.getStatus(), 200);
    Document doc = response.readEntity(Document.class);
    assertEquals("EntityDescriptor", doc.getDocumentElement().getLocalName());
    // Now validate the signature
    Element signature = (Element) doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature").item(0);
    assertNotNull(signature);
    XMLSignature signatureElem = new XMLSignature(signature, "");
    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);
    X509Certificate signingCert = signatureElem.getKeyInfo().getX509Certificate();
    assertNotNull(signingCert);
    assertTrue(signatureElem.checkSignatureValue(signingCert));
}
Also used : Response(javax.ws.rs.core.Response) XMLSignature(org.apache.xml.security.signature.XMLSignature) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate)

Example 62 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project cxf by apache.

the class AbstractXmlSigInHandler method checkSignature.

protected void checkSignature(Message message) {
    Document doc = getDocument(message);
    if (doc == null) {
        return;
    }
    Element root = doc.getDocumentElement();
    Element signatureElement = getSignatureElement(root);
    if (signatureElement == null) {
        throwFault("XML Signature is not available", null);
    }
    final String cryptoKey;
    final String propKey;
    if (RSSecurityUtils.isSignedAndEncryptedTwoWay(message)) {
        cryptoKey = SecurityConstants.ENCRYPT_CRYPTO;
        propKey = SecurityConstants.ENCRYPT_PROPERTIES;
    } else {
        cryptoKey = SecurityConstants.SIGNATURE_CRYPTO;
        propKey = SecurityConstants.SIGNATURE_PROPERTIES;
    }
    Crypto crypto = null;
    try {
        CryptoLoader loader = new CryptoLoader();
        crypto = loader.getCrypto(message, cryptoKey, propKey);
    } catch (Exception ex) {
        throwFault("Crypto can not be loaded", ex);
    }
    boolean valid = false;
    Reference ref = null;
    try {
        XMLSignature signature = new XMLSignature(signatureElement, "", true);
        if (sigProps != null) {
            SignedInfo sInfo = signature.getSignedInfo();
            if (sigProps.getSignatureAlgo() != null && !sigProps.getSignatureAlgo().equals(sInfo.getSignatureMethodURI())) {
                throwFault("Signature Algorithm is not supported", null);
            }
            if (sigProps.getSignatureC14nMethod() != null && !sigProps.getSignatureC14nMethod().equals(sInfo.getCanonicalizationMethodURI())) {
                throwFault("Signature C14n Algorithm is not supported", null);
            }
        }
        ref = getReference(signature);
        Element signedElement = validateReference(root, ref);
        if (signedElement.hasAttributeNS(null, "ID")) {
            signedElement.setIdAttributeNS(null, "ID", true);
        }
        if (signedElement.hasAttributeNS(null, "Id")) {
            signedElement.setIdAttributeNS(null, "Id", true);
        }
        X509Certificate cert = null;
        PublicKey publicKey = null;
        // See also WSS4J SAMLUtil.getCredentialFromKeyInfo
        KeyInfo keyInfo = signature.getKeyInfo();
        if (keyInfo != null) {
            cert = keyInfo.getX509Certificate();
            if (cert != null) {
                valid = signature.checkSignatureValue(cert);
            } else {
                publicKey = keyInfo.getPublicKey();
                if (publicKey != null) {
                    valid = signature.checkSignatureValue(publicKey);
                }
            }
        } else if (!keyInfoMustBeAvailable) {
            String user = getUserName(crypto, message);
            cert = RSSecurityUtils.getCertificates(crypto, user)[0];
            publicKey = cert.getPublicKey();
            valid = signature.checkSignatureValue(cert);
        }
        // validate trust
        new TrustValidator().validateTrust(crypto, cert, publicKey, getSubjectContraints(message));
        if (valid && persistSignature) {
            if (signature.getKeyInfo() != null) {
                message.put(SIGNING_CERT, signature.getKeyInfo().getX509Certificate());
            }
            if (signature.getKeyInfo() != null) {
                message.put(SIGNING_PUBLIC_KEY, signature.getKeyInfo().getPublicKey());
            }
            message.setContent(Element.class, signedElement);
        }
    } catch (Exception ex) {
        throwFault("Signature validation failed", ex);
    }
    if (!valid) {
        throwFault("Signature validation failed", null);
    }
    if (removeSignature) {
        if (!isEnveloping(root)) {
            Element signedEl = getSignedElement(root, ref);
            signedEl.removeAttribute("ID");
            root.removeChild(signatureElement);
        } else {
            Element actualBody = getActualBody(root);
            Document newDoc = DOMUtils.createDocument();
            newDoc.adoptNode(actualBody);
            root = actualBody;
        }
    }
    message.setContent(XMLStreamReader.class, new W3CDOMStreamReader(root));
    message.setContent(InputStream.class, null);
}
Also used : TrustValidator(org.apache.cxf.rs.security.common.TrustValidator) Reference(org.apache.xml.security.signature.Reference) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) CryptoLoader(org.apache.cxf.rs.security.common.CryptoLoader) Document(org.w3c.dom.Document) PatternSyntaxException(java.util.regex.PatternSyntaxException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) X509Certificate(java.security.cert.X509Certificate) SignedInfo(org.apache.xml.security.signature.SignedInfo) Crypto(org.apache.wss4j.common.crypto.Crypto) KeyInfo(org.apache.xml.security.keys.KeyInfo) W3CDOMStreamReader(org.apache.cxf.staxutils.W3CDOMStreamReader) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 63 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class AMSignatureProvider method signXML.

/**  
     * Sign part of the xml document referered by the supplied a list
     * of id attributes of nodes
     * @param doc XML dom object
     * @param certAlias Signer's certificate alias name
     * @param algorithm XML signature algorithm
     * @param transformAlag XML siganture transform algorithm
     *        Those transfer constants are defined as
     *        SAMLConstants.TRANSFORM_XXX.       
     * @param ids list of id attribute values of nodes to be signed
     * @return signature dom object
     * @throws XMLSignatureException if the document could not be signed
     */
public org.w3c.dom.Element signXML(org.w3c.dom.Document doc, java.lang.String certAlias, java.lang.String algorithm, java.lang.String transformAlag, java.util.List ids) throws XMLSignatureException {
    if (doc == null) {
        SAMLUtilsCommon.debug.error("signXML: doc is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (certAlias == null || certAlias.length() == 0) {
        SAMLUtilsCommon.debug.error("signXML: certAlias is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    org.w3c.dom.Element root = doc.getDocumentElement();
    XMLSignature signature = null;
    try {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
        PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
        if (privateKey == null) {
            SAMLUtilsCommon.debug.error("private key is null");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
        }
        if (algorithm == null || algorithm.length() == 0) {
            algorithm = getKeyAlgorithm(privateKey);
        }
        if (!isValidAlgorithm(algorithm)) {
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
        }
        signature = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        root.appendChild(signature.getElement());
        int size = ids.size();
        for (int i = 0; i < size; ++i) {
            Transforms transforms = new Transforms(doc);
            if (transformAlag != null) {
                transforms.addTransform(transformAlag);
            }
            transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
            String id = (String) ids.get(i);
            if (SAMLUtilsCommon.debug.messageEnabled()) {
                SAMLUtilsCommon.debug.message("id = " + id);
            }
            signature.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
        }
        X509Certificate cert = (X509Certificate) keystore.getX509Certificate(certAlias);
        signature.addKeyInfo(cert);
        signature.sign(privateKey);
    } catch (Exception e) {
        SAMLUtilsCommon.debug.error("signXML Exception: ", e);
        throw new XMLSignatureException(e.getMessage());
    }
    return (signature.getElement());
}
Also used : org.w3c.dom(org.w3c.dom) XMLSignature(org.apache.xml.security.signature.XMLSignature) Transforms(org.apache.xml.security.transforms.Transforms) TransformerException(javax.xml.transform.TransformerException)

Example 64 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class AMSignatureProvider method signXMLUsingKeyPass.

/**
     * Sign part of the XML document referred by the supplied id attribute
     * using enveloped signatures and use exclusive XML canonicalization.
     * @param doc XML dom object
     * @param certAlias Signer's certificate alias name
     * @param encryptedKeyPass Use the supplied encrypted key password to get the private key
     * @param algorithm XML signature algorithm
     * @param idAttrName attribute name for the id attribute of the node to be
     *        signed.
     * @param id id attribute value of the node to be signed
     * @param includeCert if true, include the signing certificate in
     *        <code>KeyInfo</code>.
     *                    if false, does not include the signing certificate.
     * @param xpath expression should uniquely identify a node before which
     * @return a signed dom object
     * @throws XMLSignatureException if the document could not be signed
     */
public Element signXMLUsingKeyPass(Document doc, String certAlias, String encryptedKeyPass, String algorithm, String idAttrName, String id, boolean includeCert, String xpath) throws XMLSignatureException {
    if (doc == null) {
        SAMLUtilsCommon.debug.error("signXML: doc is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (certAlias == null || certAlias.length() == 0) {
        SAMLUtilsCommon.debug.error("signXML: certAlias is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    Element root = null;
    XMLSignature sig = null;
    try {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
        PrivateKey privateKey;
        if (encryptedKeyPass == null || encryptedKeyPass.isEmpty()) {
            privateKey = keystore.getPrivateKey(certAlias);
        } else {
            privateKey = keystore.getPrivateKey(certAlias, encryptedKeyPass);
        }
        if (privateKey == null) {
            SAMLUtilsCommon.debug.error("private key is null");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
        }
        root = (Element) XPathAPI.selectSingleNode(doc, "//*[@" + idAttrName + "=\"" + id + "\"]");
        if (root == null) {
            SAMLUtilsCommon.debug.error("signXML: could not" + " resolv id attribute");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidIDAttribute"));
        }
        // Set the ID attribute if idAttrName is not the default.
        if (!idAttrName.equals(DEF_ID_ATTRIBUTE)) {
            root.setIdAttribute(idAttrName, true);
        }
        if (algorithm == null || algorithm.length() == 0) {
            algorithm = getKeyAlgorithm(privateKey);
            ;
        }
        if (!isValidAlgorithm(algorithm)) {
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
        }
        sig = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        if (xpath == null) {
            root.appendChild(sig.getElement());
        } else {
            Node beforeNode = XPathAPI.selectSingleNode(doc, xpath);
            root.insertBefore(sig.getElement(), beforeNode);
        }
        sig.getSignedInfo().addResourceResolver(new OfflineResolver());
        // do transform   
        Transforms transforms = new Transforms(doc);
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
        String ref = "#" + id;
        sig.addDocument(ref, transforms, Constants.ALGO_ID_DIGEST_SHA1);
        if (includeCert) {
            X509Certificate cert = (X509Certificate) keystore.getX509Certificate(certAlias);
            sig.addKeyInfo(cert);
        }
        sig.sign(privateKey);
    } catch (Exception e) {
        SAMLUtilsCommon.debug.error("signXML Exception: ", e);
        throw new XMLSignatureException(e.getMessage());
    }
    return (sig.getElement());
}
Also used : XMLSignature(org.apache.xml.security.signature.XMLSignature) Transforms(org.apache.xml.security.transforms.Transforms) TransformerException(javax.xml.transform.TransformerException)

Example 65 with XMLSignature

use of org.apache.xml.security.signature.XMLSignature in project OpenAM by OpenRock.

the class AMSignatureProvider method signXML.

/**
     * Sign the xml document using enveloped signatures.
     * @param doc XML dom object 
     * @param certAlias Signer's certificate alias name
     * @param algorithm XML signature algorithm 
     * @return signature dom object 
     * @throws XMLSignatureException if the document could not be signed
     */
public org.w3c.dom.Element signXML(org.w3c.dom.Document doc, java.lang.String certAlias, java.lang.String algorithm) throws XMLSignatureException {
    if (doc == null) {
        SAMLUtilsCommon.debug.error("signXML: doc is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    if (certAlias == null || certAlias.length() == 0) {
        SAMLUtilsCommon.debug.error("signXML: certAlias is null.");
        throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    org.w3c.dom.Element root = null;
    XMLSignature sig = null;
    try {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
        if (keystore == null) {
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullkeystore"));
        }
        PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
        if (privateKey == null) {
            SAMLUtilsCommon.debug.error("private key is null");
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
        }
        root = doc.getDocumentElement();
        if (algorithm == null || algorithm.length() == 0) {
            algorithm = getKeyAlgorithm(privateKey);
        }
        if (!isValidAlgorithm(algorithm)) {
            throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
        }
        if (c14nMethod == null || c14nMethod.length() == 0) {
            sig = new XMLSignature(doc, "", algorithm);
        } else {
            if (!isValidCanonicalizationMethod(c14nMethod)) {
                throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidCanonicalizationMethod"));
            }
            sig = new XMLSignature(doc, "", algorithm, c14nMethod);
        }
        root.appendChild(sig.getElement());
        sig.getSignedInfo().addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
        // do transform 
        Transforms transforms = new Transforms(doc);
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        // such transform due to performance reason.    
        if (transformAlg != null && transformAlg.length() != 0) {
            if (!isValidTransformAlgorithm(transformAlg)) {
                throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidTransformAlgorithm"));
            }
            transforms.addTransform(transformAlg);
        }
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
        // add certificate 
        X509Certificate cert = (X509Certificate) keystore.getX509Certificate(certAlias);
        sig.addKeyInfo(cert);
        sig.sign(privateKey);
    } catch (Exception e) {
        SAMLUtilsCommon.debug.error("signXML Exception: ", e);
        throw new XMLSignatureException(e.getMessage());
    }
    return (sig.getElement());
}
Also used : org.w3c.dom(org.w3c.dom) Transforms(org.apache.xml.security.transforms.Transforms) TransformerException(javax.xml.transform.TransformerException) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Aggregations

XMLSignature (org.apache.xml.security.signature.XMLSignature)132 Document (org.w3c.dom.Document)91 Element (org.w3c.dom.Element)69 X509Certificate (java.security.cert.X509Certificate)60 Test (org.junit.Test)55 DocumentBuilder (javax.xml.parsers.DocumentBuilder)52 InputStream (java.io.InputStream)51 ByteArrayInputStream (java.io.ByteArrayInputStream)50 ByteArrayOutputStream (java.io.ByteArrayOutputStream)49 KeyStore (java.security.KeyStore)48 ArrayList (java.util.ArrayList)48 XMLStreamReader (javax.xml.stream.XMLStreamReader)43 Key (java.security.Key)42 DOMSource (javax.xml.transform.dom.DOMSource)42 StreamResult (javax.xml.transform.stream.StreamResult)42 Transforms (org.apache.xml.security.transforms.Transforms)29 SecretKey (javax.crypto.SecretKey)28 XPath (javax.xml.xpath.XPath)23 KeyInfo (org.apache.xml.security.keys.KeyInfo)22 XPathFactory (javax.xml.xpath.XPathFactory)19