Java Code Examples for javax.xml.crypto.dsig.XMLSignature#validate()

The following examples show how to use javax.xml.crypto.dsig.XMLSignature#validate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestValidator.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public Result validate ( final Document doc ) throws Exception
{
    final NodeList nl = doc.getElementsByTagNameNS ( XMLSignature.XMLNS, "Signature" ); //$NON-NLS-1$

    if ( nl.getLength () == 0 )
    {
        return new Result ( StatusCodes.VALIDATE_NO_SIGNATURE_DATA, "No signature data found" );
    }

    final DOMValidateContext dvc = new DOMValidateContext ( this.keySelector, nl.item ( 0 ) );

    final XMLSignature signature = this.factory.unmarshalXMLSignature ( dvc );

    try
    {
        final boolean result = signature.validate ( dvc );

        return new Result ( result, signature );
    }
    catch ( final XMLSignatureException e )
    {
        logger.debug ( "Failed to perform validation", e );
        return Result.INVALID;
    }
}
 
Example 2
Source File: XML.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 * Check the xmldsig signature of the XML document.
 * @param document the document to test
 * @param publicKey the public key corresponding to the key pair the document was signed with
 * @return true if a correct signature is present, false otherwise
 */
public static boolean validSignature(Document document, Key publicKey) {
    Node signatureNode =  document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0);
    KeySelector keySelector = KeySelector.singletonKeySelector(publicKey);

    try {
        String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
        DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureNode);

        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        return signature.validate(valContext);
    } catch (Exception e) {
        Logger.warn("Error validating an XML signature.", e);
        return false;
    }
}
 
Example 3
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static boolean validateUsingKeySelector(Node signatureNode, KeySelector validationKeySelector) throws XMLSignatureException, MarshalException {
    DOMValidateContext valContext = new DOMValidateContext(validationKeySelector, signatureNode);
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);
    boolean coreValidity = signature.validate(valContext);
    
    if (! coreValidity) {
        if (logger.isTraceEnabled()) {
            boolean sv = signature.getSignatureValue().validate(valContext);
            logger.trace("Signature validation status: " + sv);

            List<Reference> references = signature.getSignedInfo().getReferences();
            for (Reference ref : references) {
                logger.trace("[Ref id=" + ref.getId() + ":uri=" + ref.getURI() + "]validity status:" + ref.validate(valContext));
            }
        }
    }

    return coreValidity;
}
 
Example 4
Source File: XMLDSigVerifier.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
XMLSignature getValidXMLSignature(InputStream fileStream)
        throws ParserConfigurationException,
        IOException,
        SAXException,
        MarshalException,
        XMLSignatureException,
        DOMException
{
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document xml = dBuilder.parse(fileStream);
    xml.getDocumentElement().normalize();

    // Find Signature element
    NodeList nl = xml.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0)
    {
        throw new DOMException(DOMException.INDEX_SIZE_ERR, "Missing elements");
    }

    // Create a DOM XMLSignatureFactory that will be used to unmarshal the
    // document containing the XMLSignature
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    // Create a DOMValidateContext and specify a KeyValue KeySelector
    // and document context
    DOMValidateContext valContext = new DOMValidateContext(new SigningCertSelector(), nl.item(0));

    // unmarshal the XMLSignature
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);

    boolean validSig = signature.validate(valContext);
    if(!validSig)
    {
        throw new XMLSignatureException("Invalid XML signature");
    }
    return signature;
}
 
Example 5
Source File: ErrorHandlerPermissions.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 6
Source File: XMLUtils.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean verifySignature(Document doc , X509Certificate cert) {
    try{
        if (doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").getLength() == 0)
            throw new Exception("Cannot find Signature element");

        DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0));

        XMLSignature signature = XMLSignatureFactory.getInstance("DOM").unmarshalXMLSignature(valContext);

        return signature.validate(valContext); 
    }catch(Exception e){e.printStackTrace();}
    return false;
}
 
Example 7
Source File: ErrorHandlerPermissions.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 8
Source File: ErrorHandlerPermissions.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 9
Source File: TmchXmlSignature.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that signed mark data contains a valid signature.
 *
 * <p>This method DOES NOT check if the SMD ID is revoked. It's only concerned with the
 * cryptographic stuff.
 *
 * @throws GeneralSecurityException for unsupported protocols, certs not signed by the TMCH,
 *     incorrect keys, and for invalid, old, not-yet-valid or revoked certificates.
 */
public void verify(byte[] smdXml)
    throws GeneralSecurityException, IOException, MarshalException, ParserConfigurationException,
        SAXException, XMLSignatureException {
  checkArgument(smdXml.length > 0);
  Document doc = parseSmdDocument(new ByteArrayInputStream(smdXml));

  NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
  if (signatureNodes.getLength() != 1) {
    throw new XMLSignatureException("Expected exactly one <ds:Signature> element.");
  }
  XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
  KeyValueKeySelector selector = new KeyValueKeySelector(tmchCertificateAuthority);
  DOMValidateContext context = new DOMValidateContext(selector, signatureNodes.item(0));
  XMLSignature signature = factory.unmarshalXMLSignature(context);

  boolean isValid;
  try {
    isValid = signature.validate(context);
  } catch (XMLSignatureException e) {
    throwIfInstanceOf(getRootCause(e), GeneralSecurityException.class);
    throw e;
  }
  if (!isValid) {
    throw new XMLSignatureException(explainValidationProblem(context, signature));
  }
}
 
Example 10
Source File: DigitalSignatureValidator.java    From development with Apache License 2.0 5 votes vote down vote up
private boolean validate(final DOMValidateContext validationContext)
        throws DigitalSignatureValidationException {

    try {
        // if (getLogger().isDebugLoggingEnabled()) {
        // enableReferenceCaching(validationContext);
        // }

        XMLSignatureFactory factory = XMLSignatureFactory
                .getInstance(XML_MECHANISM_TYPE);
        XMLSignature signature = factory
                .unmarshalXMLSignature(validationContext);
        boolean validationResult = signature.validate(validationContext);

        validationResult = workaroundOpenamBug(signature,
                validationContext, validationResult);

        // if (getLogger().isDebugLoggingEnabled()) {
        // debugLogReferences(signature, validationContext);
        // }
        return validationResult;
    } catch (XMLSignatureException | MarshalException exception) {
        throw new DigitalSignatureValidationException(
                "Error occurred during digital signature validation process",
                DigitalSignatureValidationException.ReasonEnum.EXCEPTION_OCCURRED,
                exception);
    }
}
 
Example 11
Source File: DigSigUtil.java    From juddi with Apache License 2.0 4 votes vote down vote up
private boolean verifySignature(Element element, PublicKey validatingKey, AtomicReference<String> OutReadableErrorMessage) {
        if (OutReadableErrorMessage == null) {
                OutReadableErrorMessage = new AtomicReference<String>();
        }
        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) {
                        logger.warn("Signature failed core validation");
                        boolean sv = signature.getSignatureValue().validate(valContext);
                        logger.debug("signature validation status: " + sv);
                        OutReadableErrorMessage.set("signature validation failed: " + sv + "." + OutReadableErrorMessage.get());
                        // 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);
                                logger.debug(j);
                                logger.debug("ref[" + j + "] validity status: " + refValid);
                                if (!refValid) {
                                        OutReadableErrorMessage.set("signature reference " + j + " invalid. " + OutReadableErrorMessage.get());
                                }
                                logger.debug("Ref type: " + ref.getType() + ", URI: " + ref.getURI());
                                for (Object xform : ref.getTransforms()) {
                                        logger.debug("Transform: " + xform);
                                }
                                String calcDigValStr = digestToString(ref.getCalculatedDigestValue());
                                String expectedDigValStr = digestToString(ref.getDigestValue());
                                logger.warn("    Calc Digest: " + calcDigValStr);
                                logger.warn("Expected Digest: " + expectedDigValStr);
                                if (!calcDigValStr.equalsIgnoreCase(expectedDigValStr)) {
                                        OutReadableErrorMessage.set("digest mismatch for signature ref " + j + "." + OutReadableErrorMessage.get());
                                }
                        }
                } else {
                        logger.info("Signature passed core validation");
                }
                return coreValidity;
        } catch (Exception e) {
                OutReadableErrorMessage.set("signature validation failed: " + e.getMessage() + OutReadableErrorMessage.get());
                logger.fatal(e);
                return false;
        }
}
 
Example 12
Source File: TckSigningUtil.java    From juddi with Apache License 2.0 4 votes vote down vote up
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);
    }
}