Search in sources :

Example 11 with XMLSignatureFactory

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

Example 12 with XMLSignatureFactory

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

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 13 with XMLSignatureFactory

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

the class XMLDigitalSignatureUtil method validate.

/**
 * Validate a XML file with a XML Digital Signature saved in an extenral file.
 *
 * @param xmlFile
 * @param xmlSignatureFile
 * @param publicKey
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
public static boolean validate(String uri, File xmlFile, File xmlSignatureFile, PublicKey publicKey) 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(publicKey, 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)

Example 14 with XMLSignatureFactory

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

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

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