Search in sources :

Example 6 with XMLSignature

use of javax.xml.crypto.dsig.XMLSignature 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)

Example 7 with XMLSignature

use of javax.xml.crypto.dsig.XMLSignature in project OpenAttestation by OpenAttestation.

the class SAMLSignature method signSAMLObject.

/**
     * Adds an enveloped signature to the given element. Then moves the
     * signature element so that it is in the correct position according to the
     * SAML assertion and protocol schema: it must immediately follow any Issuer
     * and precede everything else.
     */
public void signSAMLObject(Element target) throws GeneralSecurityException, XMLSignatureException, MarshalException {
    Reference ref = factory.newReference("#" + target.getAttribute("ID"), factory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
    SignedInfo signedInfo = factory.newSignedInfo(factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
    XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo);
    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(), target);
    signature.sign(signContext);
    // For the result to be schema-valid, we have to move the signature
    // element from its place at the end of the child list to live
    // between Issuer and Subject elements.  So, deep breath, and:
    Node signatureElement = target.getLastChild();
    boolean foundIssuer = false;
    Node elementAfterIssuer = null;
    NodeList children = target.getChildNodes();
    for (int c = 0; c < children.getLength(); ++c) {
        Node child = children.item(c);
        if (foundIssuer) {
            elementAfterIssuer = child;
            break;
        }
        if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("Issuer")) {
            foundIssuer = true;
        }
    }
    // Place after the Issuer, or as first element if no Issuer:
    if (!foundIssuer || elementAfterIssuer != null) {
        target.removeChild(signatureElement);
        target.insertBefore(signatureElement, foundIssuer ? elementAfterIssuer : target.getFirstChild());
    }
}
Also used : Reference(javax.xml.crypto.dsig.Reference) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) SignedInfo(javax.xml.crypto.dsig.SignedInfo) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Example 8 with XMLSignature

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

the class SignatureInfo method preSign.

/**
     * Helper method for adding informations before the signing.
     * Normally {@link #confirmSignature()} is sufficient to be used.
     */
@SuppressWarnings("unchecked")
public DigestInfo preSign(Document document, List<DigestInfo> digestInfos) throws XMLSignatureException, MarshalException {
    signatureConfig.init(false);
    // it's necessary to explicitly set the mdssi namespace, but the sign() method has no
    // normal way to interfere with, so we need to add the namespace under the hand ...
    EventTarget target = (EventTarget) document;
    EventListener creationListener = signatureConfig.getSignatureMarshalListener();
    if (creationListener != null) {
        if (creationListener instanceof SignatureMarshalListener) {
            ((SignatureMarshalListener) creationListener).setEventTarget(target);
        }
        SignatureMarshalListener.setListener(target, creationListener, true);
    }
    /*
         * Signature context construction.
         */
    XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.getKey(), document);
    URIDereferencer uriDereferencer = signatureConfig.getUriDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }
    for (Map.Entry<String, String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
        xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue());
    }
    xmlSignContext.setDefaultNamespacePrefix("");
    // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));
    brokenJvmWorkaround(xmlSignContext);
    XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory();
    /*
         * Add ds:References that come from signing client local files.
         */
    List<Reference> references = new ArrayList<Reference>();
    for (DigestInfo digestInfo : safe(digestInfos)) {
        byte[] documentDigestValue = digestInfo.digestValue;
        String uri = new File(digestInfo.description).getName();
        Reference reference = SignatureFacet.newReference(uri, null, null, null, documentDigestValue, signatureConfig);
        references.add(reference);
    }
    /*
         * Invoke the signature facets.
         */
    List<XMLObject> objects = new ArrayList<XMLObject>();
    for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {
        LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName());
        signatureFacet.preSign(document, references, objects);
    }
    /*
         * ds:SignedInfo
         */
    SignedInfo signedInfo;
    try {
        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(signatureConfig.getSignatureMethodUri(), null);
        CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(), (C14NMethodParameterSpec) null);
        signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);
    } catch (GeneralSecurityException e) {
        throw new XMLSignatureException(e);
    }
    /*
         * JSR105 ds:Signature creation
         */
    String signatureValueId = signatureConfig.getPackageSignatureId() + "-signature-value";
    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null, objects, signatureConfig.getPackageSignatureId(), signatureValueId);
    /*
         * ds:Signature Marshalling.
         */
    xmlSignature.sign(xmlSignContext);
    /*
         * Completion of undigested ds:References in the ds:Manifests.
         */
    for (XMLObject object : objects) {
        LOG.log(POILogger.DEBUG, "object java type: " + object.getClass().getName());
        List<XMLStructure> objectContentList = object.getContent();
        for (XMLStructure objectContent : objectContentList) {
            LOG.log(POILogger.DEBUG, "object content java type: " + objectContent.getClass().getName());
            if (!(objectContent instanceof Manifest))
                continue;
            Manifest manifest = (Manifest) objectContent;
            List<Reference> manifestReferences = manifest.getReferences();
            for (Reference manifestReference : manifestReferences) {
                if (manifestReference.getDigestValue() != null)
                    continue;
                DOMReference manifestDOMReference = (DOMReference) manifestReference;
                manifestDOMReference.digest(xmlSignContext);
            }
        }
    }
    /*
         * Completion of undigested ds:References.
         */
    List<Reference> signedInfoReferences = signedInfo.getReferences();
    for (Reference signedInfoReference : signedInfoReferences) {
        DOMReference domReference = (DOMReference) signedInfoReference;
        // ds:Reference with external digest value
        if (domReference.getDigestValue() != null)
            continue;
        domReference.digest(xmlSignContext);
    }
    /*
         * Calculation of XML signature digest value.
         */
    DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(xmlSignContext, dataStream);
    byte[] octets = dataStream.toByteArray();
    /*
         * TODO: we could be using DigestOutputStream here to optimize memory
         * usage.
         */
    MessageDigest md = CryptoFunctions.getMessageDigest(signatureConfig.getDigestAlgo());
    byte[] digestValue = md.digest(octets);
    String description = signatureConfig.getSignatureDescription();
    return new DigestInfo(digestValue, signatureConfig.getDigestAlgo(), description);
}
Also used : ArrayList(java.util.ArrayList) XMLStructure(javax.xml.crypto.XMLStructure) URIDereferencer(javax.xml.crypto.URIDereferencer) XMLSignContext(javax.xml.crypto.dsig.XMLSignContext) EventListener(org.w3c.dom.events.EventListener) MessageDigest(java.security.MessageDigest) EventTarget(org.w3c.dom.events.EventTarget) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) DOMSignedInfo(org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) Reference(javax.xml.crypto.dsig.Reference) GeneralSecurityException(java.security.GeneralSecurityException) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) XMLObject(javax.xml.crypto.dsig.XMLObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Manifest(javax.xml.crypto.dsig.Manifest) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) DOMSignedInfo(org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo) SignedInfo(javax.xml.crypto.dsig.SignedInfo) SignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) XMLSignature(javax.xml.crypto.dsig.XMLSignature)

Example 9 with XMLSignature

use of javax.xml.crypto.dsig.XMLSignature in project simba-os by cegeka.

the class Utils method validateSign.

/**
     * Validate signature (Message or Assertion).
     *
     * @param signatureElement The element we should validate
     * @param cert             The pubic cert
     * @param fingerprint      The fingerprint of the public cert
     * @return True if the sign is valid, false otherwise.
     */
public static boolean validateSign(Node signatureElement, Certificate cert, String... fingerprint) throws Exception {
    boolean res;
    DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), signatureElement);
    XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");
    try {
        XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx);
        res = xmlSignature.validate(ctx);
    } catch (MarshalException e) {
        log.error("Cannot locate Signature Node " + e.getMessage(), e);
        throw e;
    } catch (NullPointerException e) {
        log.error("Context can't be validated", e);
        throw e;
    }
    return res;
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) MarshalException(javax.xml.crypto.MarshalException) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext)

Aggregations

XMLSignature (javax.xml.crypto.dsig.XMLSignature)9 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)6 Reference (javax.xml.crypto.dsig.Reference)5 SignedInfo (javax.xml.crypto.dsig.SignedInfo)5 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)5 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)4 NodeList (org.w3c.dom.NodeList)4 ArrayList (java.util.ArrayList)3 XMLSignatureException (javax.xml.crypto.dsig.XMLSignatureException)3 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)3 Node (org.w3c.dom.Node)3 GeneralSecurityException (java.security.GeneralSecurityException)2 NoSuchProviderException (java.security.NoSuchProviderException)2 X509Certificate (java.security.cert.X509Certificate)2 KeySelector (javax.xml.crypto.KeySelector)2 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)2 SignatureMethod (javax.xml.crypto.dsig.SignatureMethod)2 Transform (javax.xml.crypto.dsig.Transform)2 XMLObject (javax.xml.crypto.dsig.XMLObject)2 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)2