Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.crypto.dsig.*;

import javax.xml.crypto.dsig.dom.DOMValidateContext;

import java.security.Key;

import java.security.SignatureException;

public class Main {
    private static final String NODE_SIGNATURE = "Signature";

    public static boolean validateDocumentByKey(final Document document, Key validatingKey)
            throws SignatureException {
        final DOMValidateContext valContext = new DOMValidateContext(validatingKey,
                getSignatureNode(document.getDocumentElement()));
        try {
            final XMLSignature signature = getXMLSignatureFactory().unmarshalXMLSignature(valContext);
            return signature.validate(valContext);
        } catch (final Exception e) {
            throw new SignatureException("Signature verification error", e);
        }
    }

    private static Node getSignatureNode(final Element rootElement) throws SignatureException {
        final NodeList nl = rootElement.getElementsByTagNameNS(XMLSignature.XMLNS, NODE_SIGNATURE);
        if (nl.getLength() == 0) {
            throw new SignatureException("Cannot find Signature element");
        }
        return nl.item(0);
    }

    private static synchronized XMLSignatureFactory getXMLSignatureFactory() {
        return XMLSignatureFactory.getInstance("DOM");
    }
}