Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * @(#) $Id:  $
   *
   * Copyright 2009/2010 by sIT Solutions,
   * A-1110 Wien, Geiselbergstr.21-25.
   * All rights reserved.
   *
   */
  package at.spardat.xma.boot.comp.data;
 
 
 
 
 
 public class XMLValidator {
     
     private final ILogger log;
     private final boolean enforceSignature;
     private final boolean enableSignature;
     private EntityResolver entityResolver;
     private PublicKey publicKey;

    

Parameters:
log Logger
enableSignature enable signature validation
enforceSignature enforce signature validation
 
     protected XMLValidator(PublicKey publicKeyILogger logboolean enableSignatureboolean enforceSignature) {
         this. = publicKey;
         this. = log;
         this. = enableSignature;
         this. = enforceSignature;
     }
     
     public static XMLValidator create(ILogger logProperties props) {
         iflog == null ) throw new NullPointerException();
         
         boolean enforce = false;
         boolean enable = true;
         
         String certificateAlias = .;
         if (props != null) {
             String strEnforceSignature = (String)props.get. );
             ifstrEnforceSignature != null ) {
                 enforce = strEnforceSignature != null && Boolean.valueOf(strEnforceSignature).booleanValue();
             }
             if (!enforce) {
                 String strAllowSignature = (String)props.get. );
                 ifstrAllowSignature!=null ) {
                    enable = Boolean.valueOf(strAllowSignature).booleanValue();
                 }
             }
             String strCertificateAlias = (String)props.get. );
             if (strCertificateAlias != null) {
                 certificateAlias = strCertificateAlias;
             }
         }
         PublicKey publicKey = null;
         try {
             publicKey = getPublicKey(logcertificateAlias);
         } catch (Exception e) {
             log.log(."Error loading certificate for XML signature validation."e);
         }
         if (publicKey == null && !enforce) {
             log.log(."Unable to load certificate for XML signature validation, alias={0}"certificateAlias);
             return null;
        }
        return new XMLValidator(publicKeylogenableenforce);
    }
    public void setEntityResolver(EntityResolver entityResolver) {
        this. = entityResolver;
    }
    private static PublicKey getPublicKey(ILogger logString certificateAliasthrows KeyStoreExceptionNoSuchAlgorithmExceptionCertificateExceptionIOException {
        String keyStore = System.getProperty("javax.net.ssl.trustStore");
        if (keyStore == null) {
            log.log(."No trust store defined. XML signature validation not available.");
            return null;
        }
        String keyStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        if (keyStorePassword == null) {
            keyStorePassword = "changeit";
        }
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
        
        Certificate certificate = ks.getCertificate(certificateAlias);
        return certificate == null ? null : certificate.getPublicKey();
      }
      
      protected boolean validateSignature(InputStream isthrows Exception {
          if (!) {
              return true;
          }
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          dbf.setNamespaceAware(true);
          DocumentBuilder docBuilder = dbf.newDocumentBuilder();
          if ( != null) {
              docBuilder.setEntityResolver();
          }
          Document doc = docBuilder.parse(is);
          // Find Signature element
          if (nl.getLength() == 0) {
              .log(."Cannot find Signature element. Not verifying document.");
              if () {
                  logDocument(doc);
                  return false;
              }
              return true;
          }
          if ( == null) {
              .log(."No key available to verify signature. Not verifying document.");
              return false;
          }
          // Create a DOM XMLSignatureFactory that will be used to unmarshal the document containing the XMLSignature
          XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); //$NON-NLS-1$
          DOMValidateContext valContext = new DOMValidateContext(nl.item(0));
          XMLSignature signature = fac.unmarshalXMLSignature(valContext);
          // Validate the XMLSignature (generated above)
          boolean coreValidity = signature.validate(valContext);
          // Check core validation status
          if (coreValidity == false) {
              .log(."Signature failed core validation");
              boolean sv = signature.getSignatureValue().validate(valContext);
              .log(."signature validation status: " + sv);
              // check the validation status of each Reference
              Iterator<Referencei = signature.getSignedInfo().getReferences().iterator();
              for (int j = 0; i.hasNext(); j++) {
                  boolean refValid = i.next().validate(valContext);
                  .log(."ref[" + j + "] validity status: " + refValid);
              }
              logDocument(doc);
              return false;
          } else {
              .log(."Signature passed core validation");
              return true;
          }
      }
    public void logDocument(Document docthrows IOExceptionTransformerException {
        if (.getLevel().intValue() <= ..intValue()) {
              ByteArrayOutputStream out = new ByteArrayOutputStream();
              printDocument(docout);
              .log(.out.toString());
          }
    }
    
    public static void printDocument(Document docOutputStream outthrows IOExceptionTransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(."no");
        transformer.setOutputProperty(."xml");
        transformer.setOutputProperty(."yes");
        transformer.setOutputProperty(."UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount""4");
        transformer.transform(new DOMSource(doc), 
             new StreamResult(new OutputStreamWriter(out"UTF-8")));
    }        
New to GrepCode? Check out our FAQ X