List of usage examples for javax.xml.crypto.dsig XMLSignature validate
boolean validate(XMLValidateContext validateContext) throws XMLSignatureException;
From source file:be.fedict.eid.dss.document.ooxml.OOXMLDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { if (null != originalDocument) { throw new IllegalArgumentException("cannot perform original document verifications"); }/*from w w w.j a va 2 s . com*/ OOXMLSignatureVerifier ooxmlSignatureVerifier = new OOXMLSignatureVerifier(); List<String> signatureResourceNames = ooxmlSignatureVerifier.getSignatureResourceNames(document); List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); for (String signatureResourceName : signatureResourceNames) { LOG.debug("signatureResourceName: " + signatureResourceName); Document signatureDocument = ooxmlSignatureVerifier .getSignatureDocument(new ByteArrayInputStream(document), signatureResourceName); if (null == signatureDocument) { continue; } NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { continue; } Element signatureElement = (Element) signatureNodeList.item(0); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); LOG.debug("validating signature: " + xmlSignature.getId()); boolean valid = xmlSignature.validate(domValidateContext); LOG.debug("signature valid: " + valid); if (!valid) { LOG.error("signature invalid"); continue; } // check OOXML's XML DSig/XAdES requirements if (!ooxmlSignatureVerifier.isValidOOXMLSignature(xmlSignature, document)) { LOG.error("Invalid OOXML Signature"); continue; } X509Certificate signingCertificate = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(signatureDocument, xmlSignature, signatureElement, signingCertificate); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * TransCellAccessToken????./*from w w w . j a v a 2 s . c om*/ * @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 ww w. j a v a 2 s . c om*/ * @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: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>//from w ww . ja va 2s.com * * 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:no.difi.sdp.client.asice.signature.CreateSignatureTest.java
private boolean verify_signature(final Signature signature2) { try {//w w w . ja va 2s .com 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:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); ZipEntry zipEntry;//from w ww . ja v a2 s .com while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(zipEntry)) { break; } } List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); if (null == zipEntry) { return signatureInfos; } XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream); NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Element signatureElement = (Element) signatureNodeList.item(idx); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); ZIPURIDereferencer dereferencer = new ZIPURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { continue; } // check whether all files have been signed properly SignedInfo signedInfo = xmlSignature.getSignedInfo(); @SuppressWarnings("unchecked") List<Reference> references = signedInfo.getReferences(); Set<String> referenceUris = new HashSet<String>(); for (Reference reference : references) { String referenceUri = reference.getURI(); referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8")); } zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(zipEntry)) { continue; } if (!referenceUris.contains(zipEntry.getName())) { LOG.warn("no ds:Reference for ZIP entry: " + zipEntry.getName()); return signatureInfos; } } if (null != originalDocument) { for (Reference reference : references) { if (null != reference.getType()) { /* * We skip XAdES and eID identity ds:Reference. */ continue; } String digestAlgo = reference.getDigestMethod().getAlgorithm(); LOG.debug("ds:Reference digest algo: " + digestAlgo); String referenceUri = reference.getURI(); LOG.debug("ds:Reference URI: " + referenceUri); byte[] digestValue = reference.getDigestValue(); org.apache.xml.security.signature.XMLSignature xmldsig = new org.apache.xml.security.signature.XMLSignature( documentSignaturesDocument, "", org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS); xmldsig.addDocument(referenceUri, null, digestAlgo); ResourceResolverSpi zipResourceResolver = new ZIPResourceResolver(originalDocument); xmldsig.addResourceResolver(zipResourceResolver); org.apache.xml.security.signature.SignedInfo apacheSignedInfo = xmldsig.getSignedInfo(); org.apache.xml.security.signature.Reference apacheReference = apacheSignedInfo.item(0); apacheReference.generateDigestValue(); byte[] originalDigestValue = apacheReference.getDigestValue(); if (!Arrays.equals(originalDigestValue, digestValue)) { throw new RuntimeException("not original document"); } } /* * So we already checked whether no files were changed, and that * no files were added compared to the original document. Still * have to check whether no files were removed. */ ZipInputStream originalZipInputStream = new ZipInputStream( new ByteArrayInputStream(originalDocument)); ZipEntry originalZipEntry; Set<String> referencedEntryNames = new HashSet<String>(); for (Reference reference : references) { if (null != reference.getType()) { continue; } referencedEntryNames.add(reference.getURI()); } while (null != (originalZipEntry = originalZipInputStream.getNextEntry())) { if (ODFUtil.isSignatureFile(originalZipEntry)) { continue; } if (!referencedEntryNames.contains(originalZipEntry.getName())) { LOG.warn("missing ds:Reference for ZIP entry: " + originalZipEntry.getName()); throw new RuntimeException( "missing ds:Reference for ZIP entry: " + originalZipEntry.getName()); } } } X509Certificate signer = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature, signatureElement, signer); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:com.alvexcore.repo.SimpleKeySelectorResult.java
private LicenseInfo getLicenseInfo(InputStream lic) { Document licenseXML = null;//from ww w .j a va 2 s .c o m try { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); licenseXML = fact.newDocumentBuilder().parse(lic); NodeList nl = licenseXML.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); DOMValidateContext valContext = new DOMValidateContext(new AlvexKeySelector(), nl.item(0)); XMLSignatureFactory sfac = XMLSignatureFactory.getInstance("DOM"); XMLSignature sgn = sfac.unmarshalXMLSignature(valContext); if (!sgn.validate(valContext)) return LicenseInfo.INVALID_LICENSE; } catch (Exception ex) { return LicenseInfo.INVALID_LICENSE; } SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); String id = licenseXML.getDocumentElement().getElementsByTagName("id").item(0).getTextContent(); String product = licenseXML.getDocumentElement().getElementsByTagName("product").item(0).getTextContent(); String owner = licenseXML.getDocumentElement().getElementsByTagName("owner").item(0).getTextContent(); String edition = licenseXML.getDocumentElement().getElementsByTagName("edition").item(0).getTextContent(); // We intentially have separate try/catch blocks. These tags may fail independently // and we'd like to prevent failed version tag from stopping dates parsing. String version = ANY_VERSION; try { version = licenseXML.getDocumentElement().getElementsByTagName("version").item(0).getTextContent(); } catch (Exception e) { } Date issued = null; Date validThru = null; try { String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0) .getTextContent(); validThru = sdf.parse(expiresStr); String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0) .getTextContent(); issued = sdf.parse(issuedStr); } catch (Exception e) { String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0) .getTextContent(); String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0) .getTextContent(); logger.warn( "Can not parse license dates. " + "Issued: " + issuedStr + ". Expires: " + expiresStr + "."); } int cores = new Integer( licenseXML.getDocumentElement().getElementsByTagName("cores").item(0).getTextContent()); int users = new Integer( licenseXML.getDocumentElement().getElementsByTagName("users").item(0).getTextContent()); return new LicenseInfo(id, owner, product, edition, version, cores, users, issued, validThru, false); }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validates the request signature. If the signature is not valid the * relevant {@link WSFaultException} is thrown * * @param signatureNode//from ww w . j a v a2 s . com * not null * @param signature * not null */ private void validateSignature(Node signatureNode, Signature signature, Node timestampNode) { assert signatureNode != null; assert signature != null; assert timestampNode != null; XMLSignatureFactory fac = XMLSignatureFactory.getInstance(); DOMValidateContext valContext = new DOMValidateContext(signature.getCertificate().getPublicKey(), signatureNode); try { XMLSignature xmlSignature = fac.unmarshalXMLSignature(valContext); if (!xmlSignature.validate(valContext)) { throw new WSFaultException(FaultKey.WSSE_FAILED_CHECK, "Signature is invalid."); } validateCanonicalizationMethod(xmlSignature); validateSignatureReferences(xmlSignature, valContext, signatureNode.getOwnerDocument(), timestampNode); } catch (MarshalException e) { throw new WSFaultException(FaultKey.WSSE_FAILED_CHECK, e); } catch (XMLSignatureException e) { throw new WSFaultException(FaultKey.WSSE_FAILED_CHECK, e); } }
From source file:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java
/** * Load a trusted list for the specified URL * * @param url/*from ww w. ja v a 2 s. co m*/ * @param signerCert * @return * @throws IOException */ private TrustStatusList getTrustStatusList(String url, X509Certificate signerCert) { InputStream input = null; try { input = dataLoader.get(url); if (input == null) { throw new DSSNullReturnedException("The loader returned a null InputStream for: " + url); } if (url.toLowerCase().endsWith(".zip")) { input = getZippedData(input); } Document doc = DSSXMLUtils.buildDOM(input); boolean coreValidity = true; if (checkSignature) { coreValidity = false; if (signerCert != null) { final NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodeList.getLength() == 0) { throw new DSSException("Not ETSI compliant signature. The Xml is not signed."); } if (signatureNodeList.getLength() > 1) { throw new DSSException("Not ETSI compliant signature. There is more than one signature."); } final Element signatureEl = (Element) signatureNodeList.item(0); final KeySelector keySelector = KeySelector.singletonKeySelector(signerCert.getPublicKey()); final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureEl); final TSLURIDereferencer tsluriDereferencer = new TSLURIDereferencer(signatureEl); valContext.setURIDereferencer(tsluriDereferencer); final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); final XMLSignature signature = factory.unmarshalXMLSignature(valContext); coreValidity = signature.validate(valContext); LOG.info("The TSL signature validity: " + coreValidity); } } final TrustStatusList tsl = TrustServiceListFactory.newInstance(doc); tsl.setWellSigned(coreValidity); return tsl; } catch (DSSException e) { throw e; } catch (Exception e) { throw new DSSException(e); } finally { DSSUtils.closeQuietly(input); } }
From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] documentData, byte[] originalDocument) throws Exception { Document document = this.documentBuilder.parse(new ByteArrayInputStream(documentData)); List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { LOG.debug("no XML signature found"); return signatureInfos; }//from w w w . ja va2 s . c o m XAdESValidation xadesValidation = new XAdESValidation(this.context); for (int signatureNodeIdx = 0; signatureNodeIdx < signatureNodeList.getLength(); signatureNodeIdx++) { /* * Check signature. */ Element signatureElement = (Element) signatureNodeList.item(signatureNodeIdx); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keyInfoKeySelector, signatureElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); XMLSignature xmlSignature; try { xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); } catch (MarshalException e) { LOG.error("XML signature marshalling error: " + e.getMessage(), e); continue; } LOG.debug("validating signature: " + xmlSignature.getId()); boolean signatureValid = xmlSignature.validate(domValidateContext); LOG.debug("signature valid: " + signatureValid); if (!signatureValid) { LOG.error("invalid signature"); throw new RuntimeException("invalid signature"); } if (null != originalDocument) { Document originalDomDocument = XAdESUtils.loadDocument(originalDocument); LOG.debug("performing original document verification"); verifyCoSignatureReference(xmlSignature, originalDomDocument); LOG.debug("original document verified"); } else { /* * We can still check whether the co-signature ds:Reference is * indeed doing a co-signature. */ verifyCoSignatureReference(xmlSignature, document); } X509Certificate signingCertificate = keyInfoKeySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(document, xmlSignature, signatureElement, signingCertificate); signatureInfos.add(signatureInfo); } return signatureInfos; }