Search in sources :

Example 1 with XMLSignatureException

use of javax.xml.crypto.dsig.XMLSignatureException in project poi by apache.

the class SignatureFacet method newReference.

public static Reference newReference(String uri, List<Transform> transforms, String type, String id, byte[] digestValue, SignatureConfig signatureConfig) throws XMLSignatureException {
    // the references appear in the package signature or the package object
    // so we can use the default digest algorithm
    String digestMethodUri = signatureConfig.getDigestMethodUri();
    XMLSignatureFactory sigFac = signatureConfig.getSignatureFactory();
    DigestMethod digestMethod;
    try {
        digestMethod = sigFac.newDigestMethod(digestMethodUri, null);
    } catch (GeneralSecurityException e) {
        throw new XMLSignatureException("unknown digest method uri: " + digestMethodUri, e);
    }
    Reference reference;
    if (digestValue == null) {
        reference = sigFac.newReference(uri, digestMethod, transforms, type, id);
    } else {
        reference = sigFac.newReference(uri, digestMethod, transforms, type, id, digestValue);
    }
    brokenJvmWorkaround(reference);
    return reference;
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) Reference(javax.xml.crypto.dsig.Reference) GeneralSecurityException(java.security.GeneralSecurityException) DOMDigestMethod(org.apache.jcp.xml.dsig.internal.dom.DOMDigestMethod) DigestMethod(javax.xml.crypto.dsig.DigestMethod) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 2 with XMLSignatureException

use of javax.xml.crypto.dsig.XMLSignatureException in project camel by apache.

the class XmlSignerProcessor method sign.

protected Document sign(final Message out) throws Exception {
    try {
        XMLSignatureFactory fac;
        // not work
        try {
            fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
        } catch (NoSuchProviderException ex) {
            fac = XMLSignatureFactory.getInstance("DOM");
        }
        final Node node = getMessageBodyNode(out);
        if (getConfiguration().getKeyAccessor() == null) {
            throw new XmlSignatureNoKeyException("Key accessor is missing for XML signature generation. Specify a key accessor in the configuration.");
        }
        final KeySelector keySelector = getConfiguration().getKeyAccessor().getKeySelector(out);
        if (keySelector == null) {
            throw new XmlSignatureNoKeyException("Key selector is missing for XML signature generation. Specify a key selector in the configuration.");
        }
        SignatureType signatureType = determineSignatureType(out);
        final List<String> contentReferenceUris = getContentReferenceUris(out, signatureType, node);
        Node lastParent = null;
        // only in the detached case there can be several
        for (final String contentReferenceUri : contentReferenceUris) {
            // the method KeyAccessor.getKeyInfo must be called after the method KeyAccessor.getKeySelector, this is part of the interface contract!
            // and this method must be called within the loop over the content reference URIs, because for each signature the key info ID must be different
            final KeyInfo keyInfo = getConfiguration().getKeyAccessor().getKeyInfo(out, node, fac.getKeyInfoFactory());
            String signatureId = getConfiguration().getSignatureId();
            if (signatureId == null) {
                signatureId = "_" + UUID.randomUUID().toString();
            } else if (signatureId.isEmpty()) {
                // indicator that no signature Id attribute shall be generated
                signatureId = null;
            }
            // parent only relevant for enveloped or detached signature
            Node parent = getParentOfSignature(out, node, contentReferenceUri, signatureType);
            if (parent == null) {
                // for enveloping signature, create new document 
                parent = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).newDocument();
            }
            lastParent = parent;
            XmlSignatureProperties.Input input = new InputBuilder().contentDigestAlgorithm(getDigestAlgorithmUri()).keyInfo(keyInfo).message(out).messageBodyNode(node).parent(parent).signatureAlgorithm(getConfiguration().getSignatureAlgorithm()).signatureFactory(fac).signatureId(signatureId).contentReferenceUri(contentReferenceUri).signatureType(signatureType).prefixForXmlSignatureNamespace(getConfiguration().getPrefixForXmlSignatureNamespace()).build();
            XmlSignatureProperties.Output properties = getSignatureProperties(input);
            // the signature properties can overwrite the signature Id
            if (properties != null && properties.getSignatureId() != null && !properties.getSignatureId().isEmpty()) {
                signatureId = properties.getSignatureId();
            }
            List<? extends XMLObject> objects = getObjects(input, properties);
            List<? extends Reference> refs = getReferences(input, properties, getKeyInfoId(keyInfo));
            SignedInfo si = createSignedInfo(fac, refs);
            DOMSignContext dsc = createAndConfigureSignContext(parent, keySelector);
            XMLSignature signature = fac.newXMLSignature(si, keyInfo, objects, signatureId, null);
            // generate the signature
            signature.sign(dsc);
        }
        return XmlSignatureHelper.getDocument(lastParent);
    } catch (XMLSignatureException se) {
        if (se.getCause() instanceof InvalidKeyException) {
            throw new XmlSignatureInvalidKeyException(se.getMessage(), se);
        } else {
            throw new XmlSignatureException(se);
        }
    } catch (GeneralSecurityException e) {
        // like NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException
        throw new XmlSignatureException(e);
    }
}
Also used : XmlSignatureInvalidKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidKeyException) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XmlSignatureProperties(org.apache.camel.component.xmlsecurity.api.XmlSignatureProperties) Node(org.w3c.dom.Node) GeneralSecurityException(java.security.GeneralSecurityException) SignatureType(org.apache.camel.component.xmlsecurity.api.SignatureType) KeySelector(javax.xml.crypto.KeySelector) InvalidKeyException(java.security.InvalidKeyException) XmlSignatureInvalidKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidKeyException) SignedInfo(javax.xml.crypto.dsig.SignedInfo) XmlSignatureException(org.apache.camel.component.xmlsecurity.api.XmlSignatureException) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) XmlSignatureNoKeyException(org.apache.camel.component.xmlsecurity.api.XmlSignatureNoKeyException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 3 with XMLSignatureException

use of javax.xml.crypto.dsig.XMLSignatureException in project santuario-java by apache.

the class PhaosXMLDSig3Test method test_signature_hmac_sha1_40_exclusive_c14n_comments_detached.

@org.junit.Test
public void test_signature_hmac_sha1_40_exclusive_c14n_comments_detached() throws Exception {
    String file = "signature-hmac-sha1-40-exclusive-c14n-comments-detached.xml";
    KeySelector ks = new KeySelectors.SecretKeySelector("test".getBytes(StandardCharsets.US_ASCII));
    try {
        validator.validate(file, ks);
        fail("Expected HMACOutputLength Exception");
    } catch (XMLSignatureException xse) {
    // System.out.println(xse.getMessage());
    // pass
    }
}
Also used : KeySelector(javax.xml.crypto.KeySelector) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 4 with XMLSignatureException

use of javax.xml.crypto.dsig.XMLSignatureException in project santuario-java by apache.

the class JSRForbiddenReferenceTest method testLocalFilesystem.

@org.junit.Test
public void testLocalFilesystem() throws Exception {
    String file = "signature-external-c14n-xmlatrs.xml";
    DOMValidateContext vc = validator.getValidateContext(file, new KeySelectors.SecretKeySelector("secret".getBytes(StandardCharsets.US_ASCII)));
    vc.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.FALSE);
    boolean coreValidity = validator.validate(vc);
    assertTrue("Signature failed core validation", coreValidity);
    vc.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
    try {
        validator.validate(vc);
        fail("Failure expected when secure validation is enabled");
    } catch (XMLSignatureException ex) {
        assertTrue(ex.getMessage().contains("URIReferenceException"));
    }
}
Also used : KeySelectors(javax.xml.crypto.test.KeySelectors) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Example 5 with XMLSignatureException

use of javax.xml.crypto.dsig.XMLSignatureException in project camel by apache.

the class XmlVerifierProcessor method verify.

@SuppressWarnings("unchecked")
protected void verify(InputStream input, final Message out) throws Exception {
    //NOPMD
    LOG.debug("Verification of XML signature document started");
    final Document doc = parseInput(input, out);
    XMLSignatureFactory fac;
    // not work
    try {
        fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig");
    } catch (NoSuchProviderException ex) {
        fac = XMLSignatureFactory.getInstance("DOM");
    }
    KeySelector selector = getConfiguration().getKeySelector();
    if (selector == null) {
        throw new IllegalStateException("Wrong configuration. Key selector is missing.");
    }
    DOMValidateContext valContext = new DOMValidateContext(selector, doc);
    valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE);
    if (getConfiguration().getSecureValidation() == Boolean.TRUE) {
        valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE);
        valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
    }
    setUriDereferencerAndBaseUri(valContext);
    setCryptoContextProperties(valContext);
    NodeList signatureNodes = getSignatureNodes(doc);
    List<XMLObject> collectedObjects = new ArrayList<XMLObject>(3);
    List<Reference> collectedReferences = new ArrayList<Reference>(3);
    int totalCount = signatureNodes.getLength();
    for (int i = 0; i < totalCount; i++) {
        Element signatureNode = (Element) signatureNodes.item(i);
        valContext.setNode(signatureNode);
        final XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        if (getConfiguration().getXmlSignatureChecker() != null) {
            XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc).keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode).objects(signature.getObjects()).signatureValue(signature.getSignatureValue()).signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount).xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build();
            getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput);
        }
        boolean coreValidity;
        try {
            coreValidity = signature.validate(valContext);
        } catch (XMLSignatureException se) {
            throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se);
        }
        // Check core validation status
        boolean goon = coreValidity;
        if (!coreValidity) {
            goon = handleSignatureValidationFailed(valContext, signature);
        }
        if (goon) {
            LOG.debug("XML signature {} verified", i + 1);
        } else {
            throw new XmlSignatureInvalidException("XML signature validation failed");
        }
        collectedObjects.addAll(signature.getObjects());
        collectedReferences.addAll(signature.getSignedInfo().getReferences());
    }
    map2Message(collectedReferences, collectedObjects, out, doc);
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XmlSignatureInvalidException(org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidException) Reference(javax.xml.crypto.dsig.Reference) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) XmlSignatureChecker(org.apache.camel.component.xmlsecurity.api.XmlSignatureChecker) ArrayList(java.util.ArrayList) XMLObject(javax.xml.crypto.dsig.XMLObject) Document(org.w3c.dom.Document) KeySelector(javax.xml.crypto.KeySelector) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) NoSuchProviderException(java.security.NoSuchProviderException) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException)

Aggregations

XMLSignatureException (javax.xml.crypto.dsig.XMLSignatureException)13 KeySelector (javax.xml.crypto.KeySelector)5 Reference (javax.xml.crypto.dsig.Reference)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)4 GeneralSecurityException (java.security.GeneralSecurityException)3 ArrayList (java.util.ArrayList)3 XMLSignature (javax.xml.crypto.dsig.XMLSignature)3 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)3 Element (org.w3c.dom.Element)3 File (java.io.File)2 NoSuchProviderException (java.security.NoSuchProviderException)2 SignedInfo (javax.xml.crypto.dsig.SignedInfo)2 XMLObject (javax.xml.crypto.dsig.XMLObject)2 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)2 KeySelectors (javax.xml.crypto.test.KeySelectors)2 DOMReference (org.apache.jcp.xml.dsig.internal.dom.DOMReference)2 Document (org.w3c.dom.Document)2 NodeList (org.w3c.dom.NodeList)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 URI (java.net.URI)1