Search in sources :

Example 1 with SignedInfo

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

use of javax.xml.crypto.dsig.SignedInfo 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 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 XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
        final List<Transform> envelopedTransform = Collections.singletonList(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 RuntimeException("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, Collections.singletonList(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(Collections.singletonList(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 RuntimeException("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) XSString(org.opensaml.core.xml.schema.XSString) 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 3 with SignedInfo

use of javax.xml.crypto.dsig.SignedInfo in project wildfly by wildfly.

the class TestServlet method signDocument.

private static void signDocument(final Document doc, final PrivateKey privateKey) throws Exception {
    final XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM");
    final Reference ref = xsf.newReference("", xsf.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(xsf.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
    final SignedInfo si = xsf.newSignedInfo(xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xsf.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null), Collections.singletonList(ref));
    final KeyInfo ki = KeyInfoFactory.getInstance().newKeyInfo(Collections.singletonList(KeyInfoFactory.getInstance().newKeyName("dummy")));
    xsf.newXMLSignature(si, ki).sign(new DOMSignContext(privateKey, doc.getDocumentElement()));
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) Reference(javax.xml.crypto.dsig.Reference) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) SignedInfo(javax.xml.crypto.dsig.SignedInfo) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Example 4 with SignedInfo

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

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

Aggregations

SignedInfo (javax.xml.crypto.dsig.SignedInfo)5 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)5 Reference (javax.xml.crypto.dsig.Reference)4 XMLSignature (javax.xml.crypto.dsig.XMLSignature)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)4 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)3 Node (org.w3c.dom.Node)3 GeneralSecurityException (java.security.GeneralSecurityException)2 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)2 SignatureMethod (javax.xml.crypto.dsig.SignatureMethod)2 XMLSignatureException (javax.xml.crypto.dsig.XMLSignatureException)2 C14NMethodParameterSpec (javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 InvalidKeyException (java.security.InvalidKeyException)1 MessageDigest (java.security.MessageDigest)1 NoSuchProviderException (java.security.NoSuchProviderException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1