Java XML Transform Usage verifySignature(Element element, PublicKey validatingKey)

Here you can find the source of verifySignature(Element element, PublicKey validatingKey)

Description

verify Signature

License

Apache License

Declaration

public static boolean verifySignature(Element element,
            PublicKey validatingKey) 

Method Source Code

//package com.java2s;
/*/*from  ww  w  . j  a  v  a  2s.  c  o m*/
 * Copyright 2001-2008 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;

import java.security.PublicKey;

import java.util.Iterator;

import javax.xml.crypto.dsig.Reference;

import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;

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

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static boolean verifySignature(Element element,
            PublicKey validatingKey) {
        XMLSignatureFactory fac = initXMLSigFactory();
        NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS,
                "Signature");
        if (nl.getLength() == 0) {
            throw new RuntimeException("Cannot find Signature element");
        }
        DOMValidateContext valContext = new DOMValidateContext(
                validatingKey, nl.item(0));
        try {
            valContext.setProperty("javax.xml.crypto.dsig.cacheReference",
                    Boolean.TRUE);
            XMLSignature signature = fac.unmarshalXMLSignature(valContext);
            boolean coreValidity = signature.validate(valContext);
            // Check core validation status.
            if (coreValidity == false) {
                System.err.println("Signature failed core validation");
                boolean sv = signature.getSignatureValue().validate(
                        valContext);
                System.out.println("signature validation status: " + sv);
                // Check the validation status of each Reference.
                @SuppressWarnings("unchecked")
                Iterator<Reference> i = signature.getSignedInfo()
                        .getReferences().iterator();
                System.out
                        .println("---------------------------------------------");
                for (int j = 0; i.hasNext(); j++) {
                    Reference ref = (Reference) i.next();
                    boolean refValid = ref.validate(valContext);
                    System.out.println("ref[" + j + "] validity status: "
                            + refValid);
                    System.out.println("Ref type: " + ref.getType()
                            + ", URI: " + ref.getURI());
                    for (Object xform : ref.getTransforms()) {
                        System.out.println("Transform: " + xform);
                    }
                    String calcDigValStr = digestToString(ref
                            .getCalculatedDigestValue());
                    String expectedDigValStr = digestToString(ref
                            .getDigestValue());
                    System.out.println("    Calc Digest: " + calcDigValStr);
                    System.out.println("Expected Digest: "
                            + expectedDigValStr);
                    InputStream is = ref.getDigestInputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    is.close();
                    System.out
                            .println("---------------------------------------------");
                }
            } else {
                System.out.println("Signature passed core validation");
            }
            return coreValidity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static XMLSignatureFactory initXMLSigFactory() {
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance();
        return fac;
    }

    private static String digestToString(byte[] digest) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}

Related

  1. safeToXml(Element element)
  2. streamSource(File file)
  3. toNonValidatingSAXSource(InputStream in)
  4. toXMLInputSource(StreamSource in)
  5. unwrapException(Throwable t)
  6. writeElementContent(XMLInputFactory inputFactory, XMLStreamWriter writer, Element element)
  7. writeXhtml(InputStream inputStream, Writer writer, Templates... templates)
  8. xsl(File inFile, File outFile, InputStream xslStream)