List of usage examples for javax.xml.crypto.dsig XMLSignature getSignatureValue
SignatureValue getSignatureValue();
XMLSignature
. From source file:gov.niem.ws.util.SecurityUtil.java
public static boolean validateDocumentSignature(Document signedDoc, Key publicKey) throws MarshalException, XMLSignatureException { if (signedDoc == null) throw new IllegalArgumentException("Signed Document is null"); NodeList nl = signedDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl == null || nl.getLength() == 0) { throw new IllegalArgumentException("Cannot find Signature element"); }/*from w w w. j a v a 2s . co m*/ if (publicKey == null) throw new IllegalArgumentException("Public Key is null"); DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0)); XMLSignature signature = signatureFactory.unmarshalXMLSignature(valContext); boolean coreValidity = signature.validate(valContext); if (!coreValidity) { boolean sv = signature.getSignatureValue().validate(valContext); log.fine("Signature validation status: " + sv); } return coreValidity; }
From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Used to verify an enveloped digital signature * * @param doc a Document object containing the xml with the signature * @param keyStorePath a String containing the path to the KeyStore * @param keyStorePW a String containing the KeyStore password * @param verifyAlias a String containing the alias of the public key used for verification * @return True if signature passes verification, False otherwise *//* w w w. ja va 2 s. c om*/ public static boolean verifySignature(Document doc, String keyStorePath, String keyStorePW, String verifyAlias) { boolean coreValidation = false; PublicKey publicKey = ClientUtil.getPublicKeyByAlias(keyStorePath, keyStorePW, verifyAlias); if (publicKey == null) { logger.error( "Public key was null when verifying signature. Ensure keystore configuration values are set properly."); return false; } try { NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { logger.error("No XML Digital Signature was found. The document was discarded."); return false; } Node signatureNode = nl.item(nl.getLength() - 1); DOMValidateContext valContext = new DOMValidateContext(publicKey, signatureNode); valContext.setURIDereferencer(new MyURIDereferencer(signatureNode.getParentNode())); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = fac.unmarshalXMLSignature(valContext); coreValidation = signature.validate(valContext); if (!coreValidation) { // for testing/debugging when validation fails... logger.error("Digital Signature Core Validation failed."); boolean signatureValidation = signature.getSignatureValue().validate(valContext); logger.debug("Digital Signature Validation: " + signatureValidation); @SuppressWarnings("rawtypes") Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { Reference ref = (Reference) i.next(); boolean referenceValidation = ref.validate(valContext); logger.debug("Digital Signature Reference Validation: " + referenceValidation); byte[] calculatedDigestValue = ref.getCalculatedDigestValue(); byte[] digestValue = ref.getDigestValue(); String cdvString = new String(Base64.encodeBase64(calculatedDigestValue)); logger.debug("Digital Signature Calculated Digest Value: " + cdvString); String dvString = new String(Base64.encodeBase64(digestValue)); logger.debug("Digital Signature Digest Value: " + dvString); } } } catch (MarshalException e) { logger.error("MarshalException when attempting to verify a digital signature."); } catch (XMLSignatureException e) { logger.error("XMLSignature Exception when attempting to verify a digital signature."); } return coreValidation; }
From source file:com.helger.peppol.httpclient.SMPHttpResponseHandlerSigned.java
private static boolean _checkSignature(@Nonnull @WillClose final InputStream aEntityInputStream) throws Exception { try {/*from w w w .j av a 2 s . co m*/ // Get response from servlet final Document aDocument = DOMReader.readXMLDOM(aEntityInputStream); // We make sure that the XML is a Signed. If not, we don't have to check // any certificates. // Find Signature element. final NodeList aNodeList = aDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (aNodeList == null || aNodeList.getLength() == 0) throw new IllegalArgumentException("Element <Signature> not found in SMP XML response"); // Create a DOMValidateContext and specify a KeySelector // and document context. final X509KeySelector aKeySelector = new X509KeySelector(); final DOMValidateContext aValidateContext = new DOMValidateContext(aKeySelector, aNodeList.item(0)); final XMLSignatureFactory aSignatureFactory = XMLSignatureFactory.getInstance("DOM"); // Unmarshal the XMLSignature. final XMLSignature aSignature = aSignatureFactory.unmarshalXMLSignature(aValidateContext); // Validate the XMLSignature. final boolean bCoreValid = aSignature.validate(aValidateContext); if (!bCoreValid) { // This code block is for debugging purposes only - it has no semantical // influence s_aLogger.info("Signature failed core validation"); final boolean bSignatureValueValid = aSignature.getSignatureValue().validate(aValidateContext); s_aLogger.info(" Signature value valid: " + bSignatureValueValid); if (!bSignatureValueValid) { // Check the validation status of each Reference. int nIndex = 0; final Iterator<?> i = aSignature.getSignedInfo().getReferences().iterator(); while (i.hasNext()) { final boolean bRefValid = ((Reference) i.next()).validate(aValidateContext); s_aLogger.info(" Reference[" + nIndex + "] validity status: " + (bRefValid ? "valid" : "NOT valid!")); ++nIndex; } } } return bCoreValid; } finally { // Close the input stream StreamHelper.close(aEntityInputStream); } }
From source file:cl.nic.dte.util.XMLUtil.java
/** * Verifica si una firma XML embedida es válida según define * el estándar XML Signature (<a * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core * Validation</a>), y si el certificado era válido en la fecha dada. * <p>/* ww w. j a va 2 s .co m*/ * * Esta rutina <b>NO</b> verifica si el certificado embedido en * <KeyInfo> es válido (eso debe verificarlo con la autoridad * certificadora que emitió el certificado), pero si verifica que la * llave utilizada para verificar corresponde a la contenida en el * certificado. * * @param xml * el nodo <Signature> * @param date * una fecha en la que se verifica la validez del certificado * @return el resultado de la verificación * * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext) * @see cl.nic.dte.VerifyResult * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler * @see #getCertificate(XMLSignature) */ @SuppressWarnings("unchecked") public static VerifyResult verifySignature(XMLSignature signature, DOMValidateContext valContext) { try { KeyValueKeySelector ksel = (KeyValueKeySelector) valContext.getKeySelector(); X509Certificate x509 = getCertificate(signature); // Verifica que un certificado bien embedido if (x509 == null) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509"))); } // Validate the XMLSignature boolean coreValidity = signature.validate(valContext); // Check core validation status if (coreValidity == false) { boolean sv = signature.getSignatureValue().validate(valContext); if (!sv) return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_VALUE")); // check the validation status of each Reference String message = ""; for (Reference ref : (List<Reference>) signature.getSignedInfo().getReferences()) { if (!ref.validate(valContext)) { message += Utilities.verificationLabels.getString("XML_SIGNATURE_BAD_REFERENCE"); message = message.replaceAll("%1", new String(Base64.encodeBase64(ref.getCalculatedDigestValue()))); message = message.replaceAll("%2", new String(Base64.encodeBase64(ref.getDigestValue()))); message += "\n"; } } return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message); } // Verifica que la llave del certificado corresponde a la usada para // la firma if (!ksel.getPk().equals(x509.getPublicKey())) { String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_BADKEY"); return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message)); } return new VerifyResult(VerifyResult.XML_SIGNATURE_OK, true, null); } catch (XMLSignatureException e) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage())); } }
From source file:gov.nih.nci.cacis.nav.DefaultNotificationValidator.java
@Override public void validateDigitalSignature(Node sig, final XDSDocumentResolver resolver) throws NotificationValidationException { boolean valid = false; try {/* w ww. j a v a2 s .c o m*/ final DOMValidateContext valContext = new DOMValidateContext(getKeySelector(), sig); final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); final XMLSignature signature = fac.unmarshalXMLSignature(valContext); // We cannot validate the References to documents in the XDS without // first retrieving them. So, for now, we can't do "core" validation. // We can only validate the Signature itself. valid = signature.getSignatureValue().validate(valContext); // CHECKSTYLE:OFF } catch (Exception ex) { // CHECKSTYLE:ON throw new NotificationValidationException("Error validating digital signature: " + ex.getMessage(), ex); } if (!valid) { throw new NotificationValidationException(ERR_SIG_VALIDATION_FAILED_MSG); } validateDocReferences(sig, resolver); }
From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java
private boolean verify_signature(final Signature signature2) { try {// ww w. ja v a2 s . c o m signature2.getBytes(); DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); fac.setNamespaceAware(true); DocumentBuilder builder = fac.newDocumentBuilder(); final Document doc = builder.parse(new ByteArrayInputStream(signature2.getBytes())); //System.err.println(new String(signature2.getBytes())); NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); DOMValidateContext valContext = new DOMValidateContext( noekkelpar.getSertifikat().getX509Certificate().getPublicKey(), nl.item(0)); valContext.setURIDereferencer(new URIDereferencer() { @Override public Data dereference(final URIReference uriReference, final XMLCryptoContext context) throws URIReferenceException { //System.out.println("$$$$ " + uriReference.getURI()); for (AsicEAttachable file : files) { if (file.getFileName().equals(uriReference.getURI().toString())) { return new OctetStreamData(new ByteArrayInputStream(file.getBytes())); } } uriReference.getURI().toString().replace("#", ""); Node element = doc.getElementsByTagName("SignedProperties").item(0); return new DOMSubTreeData(element, false); } }); XMLSignatureFactory fact = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = fact.unmarshalXMLSignature(valContext); boolean coreValidity = signature.validate(valContext); if (coreValidity == false) { System.err.println("Signature failed core validation"); boolean sv = signature.getSignatureValue().validate(valContext); System.out.println("signature validation status: " + sv); if (sv == false) { // Check the validation status of each Reference. Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid = ((javax.xml.crypto.dsig.Reference) i.next()).validate(valContext); System.out.println("ref[" + j + "] validity status: " + refValid); } } } return coreValidity; } catch (Exception ex) { ex.printStackTrace(System.err); return false; } }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????.//from w ww . j a v a 2 s. co m * @param token * @return TransCellAccessToken(?) * @throws AbstractOAuth2Token.TokenParseException ? * @throws AbstractOAuth2Token.TokenDsigException ??? * @throws AbstractOAuth2Token.TokenRootCrtException CA? */ public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException, AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException { try { byte[] samlBytes = DcCoreUtils.decodeBase64Url(token); ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.parse(bais); Element assertion = doc.getDocumentElement(); Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0)); Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0)); Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0)); String id = assertion.getAttribute("ID"); String issuedAtStr = assertion.getAttribute("IssueInstant"); DateTime dt = new DateTime(issuedAtStr); NodeList audienceList = assertion.getElementsByTagName("Audience"); Element aud1 = (Element) (audienceList.item(0)); String target = aud1.getTextContent(); String schema = null; if (audienceList.getLength() > 1) { Element aud2 = (Element) (audienceList.item(1)); schema = aud2.getTextContent(); } List<Role> roles = new ArrayList<Role>(); NodeList attrList = assertion.getElementsByTagName("AttributeValue"); for (int i = 0; i < attrList.getLength(); i++) { Element attv = (Element) (attrList.item(i)); roles.add(new Role(new URL(attv.getTextContent()))); } NodeList nl = assertion.getElementsByTagName("Signature"); if (nl.getLength() == 0) { throw new TokenParseException("Cannot find Signature element"); } Element signatureElement = (Element) nl.item(0); // ???????TokenDsigException?? // Create a DOMValidateContext and specify a KeySelector // and document context. X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent()); DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement); // Unmarshal the XMLSignature. XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new TokenDsigException(e.getMessage(), e); } // CA?? try { x509KeySelector.readRoot(x509RootCertificateFileNames); } catch (CertificateException e) { // CA????????500 throw new TokenRootCrtException(e.getMessage(), e); } // Validate the XMLSignature x509. boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { if (e.getCause().getClass() == new KeySelectorException().getClass()) { throw new TokenDsigException(e.getCause().getMessage(), e.getCause()); } throw new TokenDsigException(e.getMessage(), e); } // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation // Check core validation status. if (!coreValidity) { // ?? boolean isDsigValid; try { isDsigValid = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!isDsigValid) { throw new TokenDsigException("Failed signature validation"); } // Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid; try { refValid = ((Reference) i.next()).validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!refValid) { throw new TokenDsigException("Failed to validate reference [" + j + "]"); } } throw new TokenDsigException("Signature failed core validation. unkwnon reason."); } return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(), subjectNameID.getTextContent(), target, roles, schema); } catch (UnsupportedEncodingException e) { throw new TokenParseException(e.getMessage(), e); } catch (SAXException e) { throw new TokenParseException(e.getMessage(), e); } catch (IOException e) { throw new TokenParseException(e.getMessage(), e); } }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????./*from w ww. j a v a 2 s. co m*/ * @param token * @return TransCellAccessToken(?) * @throws AbstractOAuth2Token.TokenParseException ? * @throws AbstractOAuth2Token.TokenDsigException ??? * @throws AbstractOAuth2Token.TokenRootCrtException CA? */ public static TransCellAccessToken parse(final String token) throws AbstractOAuth2Token.TokenParseException, AbstractOAuth2Token.TokenDsigException, AbstractOAuth2Token.TokenRootCrtException { try { byte[] samlBytes = PersoniumCoreUtils.decodeBase64Url(token); ByteArrayInputStream bais = new ByteArrayInputStream(samlBytes); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { // ???????????? throw new RuntimeException(e); } Document doc = builder.parse(bais); Element assertion = doc.getDocumentElement(); Element issuer = (Element) (doc.getElementsByTagName("Issuer").item(0)); Element subject = (Element) (assertion.getElementsByTagName("Subject").item(0)); Element subjectNameID = (Element) (subject.getElementsByTagName("NameID").item(0)); String id = assertion.getAttribute("ID"); String issuedAtStr = assertion.getAttribute("IssueInstant"); DateTime dt = new DateTime(issuedAtStr); NodeList audienceList = assertion.getElementsByTagName("Audience"); Element aud1 = (Element) (audienceList.item(0)); String target = aud1.getTextContent(); String schema = null; if (audienceList.getLength() > 1) { Element aud2 = (Element) (audienceList.item(1)); schema = aud2.getTextContent(); } List<Role> roles = new ArrayList<Role>(); NodeList attrList = assertion.getElementsByTagName("AttributeValue"); for (int i = 0; i < attrList.getLength(); i++) { Element attv = (Element) (attrList.item(i)); roles.add(new Role(new URL(attv.getTextContent()))); } NodeList nl = assertion.getElementsByTagName("Signature"); if (nl.getLength() == 0) { throw new TokenParseException("Cannot find Signature element"); } Element signatureElement = (Element) nl.item(0); // ???????TokenDsigException?? // Create a DOMValidateContext and specify a KeySelector // and document context. X509KeySelector x509KeySelector = new X509KeySelector(issuer.getTextContent()); DOMValidateContext valContext = new DOMValidateContext(x509KeySelector, signatureElement); // Unmarshal the XMLSignature. XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new TokenDsigException(e.getMessage(), e); } // CA?? try { x509KeySelector.readRoot(x509RootCertificateFileNames); } catch (CertificateException e) { // CA????????500 throw new TokenRootCrtException(e.getMessage(), e); } // Validate the XMLSignature x509. boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { if (e.getCause().getClass() == new KeySelectorException().getClass()) { throw new TokenDsigException(e.getCause().getMessage(), e.getCause()); } throw new TokenDsigException(e.getMessage(), e); } // http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation // Check core validation status. if (!coreValidity) { // ?? boolean isDsigValid; try { isDsigValid = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!isDsigValid) { throw new TokenDsigException("Failed signature validation"); } // Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid; try { refValid = ((Reference) i.next()).validate(valContext); } catch (XMLSignatureException e) { throw new TokenDsigException(e.getMessage(), e); } if (!refValid) { throw new TokenDsigException("Failed to validate reference [" + j + "]"); } } throw new TokenDsigException("Signature failed core validation. unkwnon reason."); } return new TransCellAccessToken(id, dt.getMillis(), issuer.getTextContent(), subjectNameID.getTextContent(), target, roles, schema); } catch (UnsupportedEncodingException e) { throw new TokenParseException(e.getMessage(), e); } catch (SAXException e) { throw new TokenParseException(e.getMessage(), e); } catch (IOException e) { throw new TokenParseException(e.getMessage(), e); } }
From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java
@Override public SignatureCryptographicVerification checkIntegrity(DSSDocument detachedDocument) { final SignatureCryptographicVerification scv = new SignatureCryptographicVerification(); final CertificateToken certToken = getSigningCertificate().getCertToken(); if (certToken != null) { final PublicKey publicKey = certToken.getCertificate().getPublicKey(); final KeySelector keySelector = KeySelector.singletonKeySelector(publicKey); /**/*from w w w . j a v a 2 s . co m*/ * Creating a Validation Context<br> * We create an XMLValidateContext instance containing input parameters for validating the signature. Since we * are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it * two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which * is the first entry of the NodeList we generated earlier): */ final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureElement); try { URIDereferencer dereferencer = new ExternalFileURIDereferencer(detachedDocument); valContext.setURIDereferencer(dereferencer); /** * This property controls whether or not the digested Reference objects will cache the dereferenced content * and pre-digested input for subsequent retrieval via the Reference.getDereferencedData and * Reference.getDigestInputStream methods. The default value if not specified is Boolean.FALSE. */ valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); /** * Unmarshalling the XML Signature<br> * We extract the contents of the Signature element into an XMLSignature object. This process is called * unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application * can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code: */ // These providers do not support ECDSA algorithm // factory = XMLSignatureFactory.getInstance("DOM"); // factory = XMLSignatureFactory.getInstance("DOM", "XMLDSig"); // factory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // This provider support ECDSA signature /** * ApacheXMLDSig / Apache Santuario XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory; C14N 1.0, C14N * 1.1, Exclusive C14N, Base64, Enveloped, XPath, XPath2, XSLT TransformServices)<br> * If this library is used than the same library must be used for the URIDereferencer. */ final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", xmlProvider); /** * We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and * pass it the validation context we created earlier: */ final XMLSignature signature = factory.unmarshalXMLSignature(valContext); //System.out.println("XMLSignature class: " + signature.getClass()); // Austrian specific signature //org.apache.xml.security.signature.XMLSignature signature_ = null; // try { // signature_ = new org.apache.xml.security.signature.XMLSignature(signatureElement, ""); // } catch (Exception e) { // // throw new DSSException(e); // } // signature.addResourceResolver(new XPointerResourceResolver(signatureElement)); //signature_.getSignedInfo().verifyReferences();//getVerificationResult(1); /** * In case of org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI() provider, the ID attributes need to be set * manually.<br> * The DSSXMLUtils.recursiveIdBrowse(...) method do not take into account the XML outside of the Signature * tag. It prevents some signatures to be validated.<br> * * Solution: the following lines where added: */ final Document document = signatureElement.getOwnerDocument(); final Element rootElement = document.getDocumentElement(); if (rootElement.hasAttribute(DSSXMLUtils.ID_ATTRIBUTE_NAME)) { valContext.setIdAttributeNS(rootElement, null, DSSXMLUtils.ID_ATTRIBUTE_NAME); } DSSXMLUtils.recursiveIdBrowse(valContext, rootElement); /** * Validating the XML Signature<br> * Now we are ready to validate the signature. We do this by invoking the validate method on the * XMLSignature object, and pass it the validation context as follows: */ boolean coreValidity = false; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage("Signature validation: " + e.getMessage()); } boolean signatureValidity = coreValidity; boolean dataFound = true; boolean dataHashValid = true; /** * If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure. * There are two phases in core XML Signature validation: <br> * - Signature validation (the cryptographic verification of the signature)<br> * - Reference validation (the verification of the digest of each reference in the signature)<br> * Each phase must be successful for the signature to be valid. To check if the signature failed to * cryptographically validate, we can check the status, as follows: */ try { signatureValidity = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(e.getMessage()); } @SuppressWarnings("unchecked") final List<Reference> references = signature.getSignedInfo().getReferences(); for (Reference reference : references) { boolean refHashValidity = false; try { refHashValidity = reference.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(reference.getURI() + ": " + e.getMessage()); } dataHashValid = dataHashValid && refHashValidity; if (LOG.isLoggable(Level.INFO)) { LOG.info("Reference hash validity checked: " + reference.getURI() + "=" + refHashValidity); } final Data data = reference.getDereferencedData(); dataFound = dataFound && (data != null); final InputStream digestInputStream = reference.getDigestInputStream(); if (data != null && digestInputStream != null) { // The references are saved for later treatment in -A level. try { IOUtils.copy(digestInputStream, referencesDigestOutputStream); } catch (IOException e) { } } } scv.setReferenceDataFound(dataFound); scv.setReferenceDataIntact(dataHashValid); scv.setSignatureIntegrity(signatureValidity); } catch (MarshalException e) { scv.setErrorMessage(e.getMessage()); } } else { scv.setErrorMessage( "Unable to proceed with the signature cryptographic verification. There is no signing certificate!"); } return scv; }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMXMLSignature.java
@Override public boolean equals(Object o) { if (this == o) { return true; }//from w w w .j ava 2s. c o m if (!(o instanceof XMLSignature)) { return false; } XMLSignature osig = (XMLSignature) o; boolean idEqual = (id == null ? osig.getId() == null : id.equals(osig.getId())); boolean keyInfoEqual = (ki == null ? osig.getKeyInfo() == null : ki.equals(osig.getKeyInfo())); return (idEqual && keyInfoEqual && sv.equals(osig.getSignatureValue()) && si.equals(osig.getSignedInfo()) && objects.equals(osig.getObjects())); }