Search in sources :

Example 1 with XMLSignatureFactory

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

the class SignatureConfig method getSignatureFactory.

/**
     * @return the xml signature factory (thread-local)
     */
public XMLSignatureFactory getSignatureFactory() {
    XMLSignatureFactory sigFac = signatureFactory.get();
    if (sigFac == null) {
        sigFac = XMLSignatureFactory.getInstance("DOM", getProvider());
        setSignatureFactory(sigFac);
    }
    return sigFac;
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory)

Example 2 with XMLSignatureFactory

use of javax.xml.crypto.dsig.XMLSignatureFactory 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 3 with XMLSignatureFactory

use of javax.xml.crypto.dsig.XMLSignatureFactory 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 4 with XMLSignatureFactory

use of javax.xml.crypto.dsig.XMLSignatureFactory in project cas by apereo.

the class AbstractSamlObjectBuilder method signSamlElement.

/**
 * Sign SAML element.
 *
 * @param element the element
 * @param privKey the priv key
 * @param pubKey  the pub key
 * @return the element
 */
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
    try {
        final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
        final Class<?> clazz = Class.forName(providerName);
        final XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());
        final List<Transform> envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
        // Create the SignatureMethod based on the type of key
        final SignatureMethod signatureMethod;
        final String algorithm = pubKey.getAlgorithm();
        switch(algorithm) {
            case "DSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
                break;
            case "RSA":
                signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
                break;
            default:
                throw new IllegalArgumentException("Error signing SAML element: Unsupported type of key");
        }
        final CanonicalizationMethod canonicalizationMethod = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
        // Create the SignedInfo
        final SignedInfo signedInfo = sigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, CollectionUtils.wrap(ref));
        // Create a KeyValue containing the DSA or RSA PublicKey
        final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
        final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);
        // Create a KeyInfo and add the KeyValue to it
        final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(CollectionUtils.wrap(keyValuePair));
        // Convert the JDOM document to w3c (Java XML signature API requires w3c representation)
        final Element w3cElement = toDom(element);
        // Create a DOMSignContext and specify the DSA/RSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
        final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
        dsc.setNextSibling(xmlSigInsertionPoint);
        // Marshal, generate (and sign) the enveloped signature
        final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
        signature.sign(dsc);
        return toJdom(w3cElement);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
    }
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) Reference(javax.xml.crypto.dsig.Reference) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) SignedInfo(javax.xml.crypto.dsig.SignedInfo) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) XMLSignature(javax.xml.crypto.dsig.XMLSignature) TransformParameterSpec(javax.xml.crypto.dsig.spec.TransformParameterSpec) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Transform(javax.xml.crypto.dsig.Transform)

Example 5 with XMLSignatureFactory

use of javax.xml.crypto.dsig.XMLSignatureFactory in project OpenOLAT by OpenOLAT.

the class XMLDigitalSignatureUtil method validate.

/**
 * @param uri
 * @param xmlFile
 * @param xmlSignatureFile
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
public static boolean validate(String uri, File xmlFile, File xmlSignatureFile) throws ParserConfigurationException, SAXException, IOException, MarshalException, XMLSignatureException {
    Document doc = getDocument(xmlSignatureFile);
    NodeList nl = doc.getElementsByTagName("Signature");
    if (nl.getLength() == 0) {
        return false;
    }
    DOMValidateContext validContext = new DOMValidateContext(new X509KeySelector(), nl.item(0));
    validContext.setBaseURI(uri);
    validContext.setURIDereferencer(new FileURIDereferencer(uri, xmlFile));
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    XMLSignature signature = fac.unmarshalXMLSignature(validContext);
    boolean validFlag = signature.validate(validContext);
    if (!validFlag) {
        // log and throw if not valid
        boolean sv = signature.getSignatureValue().validate(validContext);
        String msg = "signature validation status: " + sv;
        int numOfReferences = signature.getSignedInfo().getReferences().size();
        for (int j = 0; j < numOfReferences; j++) {
            Reference ref = (Reference) signature.getSignedInfo().getReferences().get(j);
            boolean refValid = ref.validate(validContext);
            msg += " ref[" + j + "] validity status: " + refValid;
        }
        log.warn(msg);
    }
    return validFlag;
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) XMLSignature(javax.xml.crypto.dsig.XMLSignature) URIReference(javax.xml.crypto.URIReference) Reference(javax.xml.crypto.dsig.Reference) NodeList(org.w3c.dom.NodeList) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) Document(org.w3c.dom.Document)

Aggregations

XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)24 XMLSignature (javax.xml.crypto.dsig.XMLSignature)17 Reference (javax.xml.crypto.dsig.Reference)16 Document (org.w3c.dom.Document)12 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)11 NodeList (org.w3c.dom.NodeList)11 URIReference (javax.xml.crypto.URIReference)10 SignedInfo (javax.xml.crypto.dsig.SignedInfo)10 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)10 ArrayList (java.util.ArrayList)8 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)8 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)7 Element (org.w3c.dom.Element)7 Transform (javax.xml.crypto.dsig.Transform)6 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)6 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)6 Node (org.w3c.dom.Node)5 SignatureMethod (javax.xml.crypto.dsig.SignatureMethod)4 XMLSignatureException (javax.xml.crypto.dsig.XMLSignatureException)4 GeneralSecurityException (java.security.GeneralSecurityException)3