Search in sources :

Example 1 with Transform

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

the class XmlSignerProcessor method getTransforms.

private List<Transform> getTransforms(XMLSignatureFactory fac, SignatureType sigType, Message message) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    String transformMethodsHeaderValue = message.getHeader(XmlSignatureConstants.HEADER_TRANSFORM_METHODS, String.class);
    if (transformMethodsHeaderValue == null) {
        List<AlgorithmMethod> configuredTrafos = getConfiguration().getTransformMethods();
        if (SignatureType.enveloped == sigType) {
            // add enveloped transform if necessary
            if (configuredTrafos.size() > 0) {
                if (!containsEnvelopedTransform(configuredTrafos)) {
                    configuredTrafos = new ArrayList<AlgorithmMethod>(configuredTrafos.size() + 1);
                    configuredTrafos.add(XmlSignatureHelper.getEnvelopedTransform());
                    configuredTrafos.addAll(getConfiguration().getTransformMethods());
                }
            } else {
                // add enveloped and C14N trafo
                configuredTrafos = new ArrayList<AlgorithmMethod>(2);
                configuredTrafos.add(XmlSignatureHelper.getEnvelopedTransform());
                configuredTrafos.add(XmlSignatureHelper.getCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE));
            }
        }
        List<Transform> transforms = new ArrayList<Transform>(configuredTrafos.size());
        for (AlgorithmMethod trafo : configuredTrafos) {
            Transform transform = fac.newTransform(trafo.getAlgorithm(), (TransformParameterSpec) trafo.getParameterSpec());
            transforms.add(transform);
            LOG.debug("Transform method: {}", trafo.getAlgorithm());
        }
        return transforms;
    } else {
        LOG.debug("Header {} with value '{}' found", XmlSignatureConstants.HEADER_TRANSFORM_METHODS, transformMethodsHeaderValue);
        String[] transformAlgorithms = transformMethodsHeaderValue.split(",");
        List<Transform> transforms = new ArrayList<Transform>(transformAlgorithms.length);
        for (String transformAlgorithm : transformAlgorithms) {
            transformAlgorithm = transformAlgorithm.trim();
            Transform transform = fac.newTransform(transformAlgorithm, (TransformParameterSpec) null);
            transforms.add(transform);
            LOG.debug("Transform method: {}", transformAlgorithm);
        }
        return transforms;
    }
}
Also used : ArrayList(java.util.ArrayList) AlgorithmMethod(javax.xml.crypto.AlgorithmMethod) Transform(javax.xml.crypto.dsig.Transform)

Example 2 with Transform

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

the class XAdESSignatureProperties method get.

@Override
public Output get(Input input) throws Exception {
    //NOPMD
    XmlSignatureProperties.Output result = new Output();
    if (!isAddSignedSignatureProperties() && !isAddSignedDataObjectPropeties()) {
        LOG.debug("XAdES signature properties are empty. Therefore no XAdES element will be added to the signature.");
        return result;
    }
    String signedPropertiesId = "_" + UUID.randomUUID().toString();
    List<Transform> transforms = Collections.emptyList();
    Reference ref = input.getSignatureFactory().newReference("#" + signedPropertiesId, input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), transforms, "http://uri.etsi.org/01903#SignedProperties", null);
    Node parent = input.getParent();
    Document doc;
    if (Node.DOCUMENT_NODE == parent.getNodeType()) {
        // enveloping
        doc = (Document) parent;
    } else {
        // enveloped
        doc = parent.getOwnerDocument();
    }
    Element qualifyingProperties = createElement("QualifyingProperties", doc, input);
    setIdAttributeFromHeader(XmlSignatureConstants.HEADER_XADES_QUALIFYING_PROPERTIES_ID, qualifyingProperties, input);
    String signatureId = input.getSignatureId();
    if (signatureId == null || signatureId.isEmpty()) {
        LOG.debug("No signature Id configured. Therefore a value is generated.");
        // generate one
        signatureId = "_" + UUID.randomUUID().toString();
        // and set to output
        result.setSignatureId(signatureId);
    }
    setAttribute(qualifyingProperties, "Target", "#" + signatureId);
    Element signedProperties = createElement("SignedProperties", doc, input);
    qualifyingProperties.appendChild(signedProperties);
    setAttribute(signedProperties, "Id", signedPropertiesId);
    signedProperties.setIdAttribute("Id", true);
    addSignedSignatureProperties(doc, signedProperties, input);
    String contentReferenceId = addSignedDataObjectProperties(doc, signedProperties, input);
    result.setContentReferenceId(contentReferenceId);
    DOMStructure structure = new DOMStructure(qualifyingProperties);
    XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(structure), null, null, null);
    result.setReferences(Collections.singletonList(ref));
    result.setObjects(Collections.singletonList(propertiesObject));
    return result;
}
Also used : Reference(javax.xml.crypto.dsig.Reference) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) DOMStructure(javax.xml.crypto.dom.DOMStructure) XMLObject(javax.xml.crypto.dsig.XMLObject) Transform(javax.xml.crypto.dsig.Transform) Document(org.w3c.dom.Document)

Example 3 with Transform

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

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

the class XMLDigitalSignatureUtil method signEmbedded.

/**
 * Produce a signed a XML file. The signature is added in the XML file.
 *
 * @param xmlFile The original XML file
 * @param xmlSignedFile The signed XML file
 * @param x509Cert
 * @param privateKey
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws NoSuchAlgorithmException
 * @throws GeneralSecurityException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws TransformerException
 */
public static void signEmbedded(File xmlFile, File xmlSignedFile, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
    Document doc = getDocument(xmlFile);
    // Create the signature factory for creating the signature.
    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> transforms = new ArrayList<Transform>();
    Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    transforms.add(envelopped);
    // Create the canonicalization transform to be applied after the XSLT.
    CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    transforms.add(c14n);
    // Create the Reference to the XML to be signed specifying the hash algorithm to be used
    // and the list of transforms to apply. Also specify the XML to be signed as the current
    // document (specified by the first parameter being an empty string).
    Reference reference = sigFactory.newReference("", sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
    // Create the Signed Info node of the signature by specifying the canonicalization method
    // to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
    SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
    // Create the KeyInfo node containing the public key information to include in the signature.
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    // Get the node to attach the signature.
    Node signatureInfoNode = doc.getDocumentElement();
    // Create a signing context using the private key.
    DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
    // Create the signature from the signing context and key info
    XMLSignature signature = sigFactory.newXMLSignature(si, ki);
    signature.sign(dsc);
    write(doc, xmlSignedFile);
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) URIReference(javax.xml.crypto.URIReference) Reference(javax.xml.crypto.dsig.Reference) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) Document(org.w3c.dom.Document) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) 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) Transform(javax.xml.crypto.dsig.Transform)

Example 5 with Transform

use of javax.xml.crypto.dsig.Transform in project openolat by klemens.

the class XMLDigitalSignatureUtil method signDetached.

/**
 * Create a separate XML file with the XML Digital Signature.
 *
 * of the specified XML file.
 * @param xmlFile The XML File to sign
 * @param outputSignatureFile Where the Digital Signature is saved
 * @param signatureDoc A DOM which hold the signature (optional but if you give one, the root element must exists)
 * @throws ParserConfigurationException
 * @throws GeneralSecurityException
 * @throws NoSuchAlgorithmException
 * @throws XMLSignatureException
 * @throws MarshalException
 * @throws TransformerException
 */
public static void signDetached(String uri, File xmlFile, File outputSignatureFile, Document signatureDoc, String keyName, X509Certificate x509Cert, PrivateKey privateKey) throws IOException, SAXException, ParserConfigurationException, NoSuchAlgorithmException, GeneralSecurityException, MarshalException, XMLSignatureException, TransformerException {
    Document doc = getDocument(xmlFile);
    // Create the signature factory for creating the signature.
    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> transforms = new ArrayList<Transform>();
    // Transform envelopped = sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    // transforms.add(envelopped);
    // Create the canonicalization transform to be applied after the XSLT.
    CanonicalizationMethod c14n = sigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    transforms.add(c14n);
    // Create the Reference to the XML to be signed specifying the hash algorithm to be used
    // and the list of transforms to apply. Also specify the XML to be signed as the current
    // document (specified by the first parameter being an empty string).
    Reference reference = sigFactory.newReference(uri, sigFactory.newDigestMethod(DigestMethod.SHA256, null), transforms, null, null);
    // Create the Signed Info node of the signature by specifying the canonicalization method
    // to use (INCLUSIVE), the signing method (RSA_SHA1), and the Reference node to be signed.
    SignedInfo si = sigFactory.newSignedInfo(c14n, sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
    // Create the KeyInfo node containing the public key information to include in the signature.
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    X509Data xd = kif.newX509Data(Collections.singletonList(x509Cert));
    List<Object> keyInfoList = new ArrayList<>();
    if (StringHelper.containsNonWhitespace(keyName)) {
        keyInfoList.add(kif.newKeyName(keyName));
    }
    keyInfoList.add(xd);
    KeyInfo ki = kif.newKeyInfo(keyInfoList);
    // Get the node to attach the signature.
    Node signatureInfoNode = doc.getDocumentElement();
    // Create a signing context using the private key.
    DOMSignContext dsc = new DOMSignContext(privateKey, signatureInfoNode);
    dsc.setBaseURI(uri);
    dsc.setURIDereferencer(new FileURIDereferencer(uri, xmlFile));
    // Create the signature from the signing context and key info
    XMLSignature signature = sigFactory.newXMLSignature(si, ki);
    signature.sign(dsc);
    NodeList nl = doc.getElementsByTagName("Signature");
    if (nl.getLength() == 1) {
        if (signatureDoc != null && signatureDoc.getDocumentElement() != null) {
            Element rootEl = signatureDoc.getDocumentElement();
            rootEl.appendChild(signatureDoc.importNode(nl.item(0), true));
            write(rootEl, outputSignatureFile);
        } else {
            write(nl.item(0), outputSignatureFile);
        }
    }
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) URIReference(javax.xml.crypto.URIReference) Reference(javax.xml.crypto.dsig.Reference) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) Document(org.w3c.dom.Document) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) 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) Transform(javax.xml.crypto.dsig.Transform)

Aggregations

Transform (javax.xml.crypto.dsig.Transform)17 Reference (javax.xml.crypto.dsig.Reference)13 ArrayList (java.util.ArrayList)10 SignedInfo (javax.xml.crypto.dsig.SignedInfo)7 XMLSignature (javax.xml.crypto.dsig.XMLSignature)7 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)7 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)7 Document (org.w3c.dom.Document)7 Node (org.w3c.dom.Node)7 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)6 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)6 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)6 Element (org.w3c.dom.Element)6 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)5 DOMStructure (javax.xml.crypto.dom.DOMStructure)4 XMLObject (javax.xml.crypto.dsig.XMLObject)4 URIReference (javax.xml.crypto.URIReference)3 InputStream (java.io.InputStream)2 URISyntaxException (java.net.URISyntaxException)2 X509Certificate (java.security.cert.X509Certificate)2