List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory unmarshalXMLSignature
public abstract XMLSignature unmarshalXMLSignature(XMLStructure xmlStructure) throws MarshalException;
XMLSignature
instance from a mechanism-specific XMLStructure
instance. 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 *//*from w w w . j a 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 2s .c o 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:be.e_contract.dssp.client.SignResponseVerifier.java
/** * Checks the signature on the SignResponse browser POST message. * /*from w ww . j a v a 2 s .co m*/ * @param signResponseMessage * the SignResponse message. * @param session * the session object. * @return the verification result object. * @throws JAXBException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws MarshalException * @throws XMLSignatureException * @throws Base64DecodingException * @throws UserCancelException * @throws ClientRuntimeException * @throws SubjectNotAuthorizedException */ public static SignResponseVerificationResult checkSignResponse(String signResponseMessage, DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException, SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException, UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException { if (null == session) { throw new IllegalArgumentException("missing session"); } byte[] decodedSignResponseMessage; try { decodedSignResponseMessage = Base64.decode(signResponseMessage); } catch (Base64DecodingException e) { throw new SecurityException("no Base64"); } // JAXB parsing JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class, be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); SignResponse signResponse; try { signResponse = (SignResponse) unmarshaller .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage)); } catch (UnmarshalException e) { throw new SecurityException("no valid SignResponse XML"); } // DOM parsing DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage); Document signResponseDocument = documentBuilder.parse(signResponseInputStream); // signature verification NodeList signatureNodeList = signResponseDocument .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (signatureNodeList.getLength() != 1) { throw new SecurityException("requires 1 ds:Signature element"); } Element signatureElement = (Element) signatureNodeList.item(0); SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey()); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validSignature = xmlSignature.validate(domValidateContext); if (false == validSignature) { throw new SecurityException("invalid ds:Signature"); } // verify content String responseId = null; RelatesToType relatesTo = null; AttributedURIType to = null; TimestampType timestamp = null; String signerIdentity = null; AnyType optionalOutputs = signResponse.getOptionalOutputs(); List<Object> optionalOutputsList = optionalOutputs.getAny(); for (Object optionalOutputObject : optionalOutputsList) { LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName()); if (optionalOutputObject instanceof JAXBElement) { JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject; LOG.debug("optional output name: " + optionalOutputElement.getName()); LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName()); if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) { responseId = (String) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof RelatesToType) { relatesTo = (RelatesToType) optionalOutputElement.getValue(); } else if (TO_QNAME.equals(optionalOutputElement.getName())) { to = (AttributedURIType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof TimestampType) { timestamp = (TimestampType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) { NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue(); signerIdentity = nameIdentifier.getValue(); } } } Result result = signResponse.getResult(); LOG.debug("result major: " + result.getResultMajor()); LOG.debug("result minor: " + result.getResultMinor()); if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) { if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) { throw new UserCancelException(); } if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) { throw new ClientRuntimeException(); } if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR .equals(result.getResultMinor())) { throw new SubjectNotAuthorizedException(signerIdentity); } } if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) { throw new SecurityException("invalid dss:ResultMajor"); } if (null == responseId) { throw new SecurityException("missing async:ResponseID"); } if (false == responseId.equals(session.getResponseId())) { throw new SecurityException("invalid async:ResponseID"); } if (null == relatesTo) { throw new SecurityException("missing wsa:RelatesTo"); } if (false == session.getInResponseTo().equals(relatesTo.getValue())) { throw new SecurityException("invalid wsa:RelatesTo"); } if (null == to) { throw new SecurityException("missing wsa:To"); } if (false == session.getDestination().equals(to.getValue())) { throw new SecurityException("invalid wsa:To"); } if (null == timestamp) { throw new SecurityException("missing wsu:Timestamp"); } AttributedDateTime expires = timestamp.getExpires(); if (null == expires) { throw new SecurityException("missing wsu:Timestamp/wsu:Expires"); } DateTime expiresDateTime = new DateTime(expires.getValue()); DateTime now = new DateTime(); if (now.isAfter(expiresDateTime)) { throw new SecurityException("wsu:Timestamp expired"); } session.setSignResponseVerified(true); SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult( signerIdentity); return signResponseVerificationResult; }
From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureVerifier.java
private static X509Certificate getVerifiedSignatureSigner(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException { if (null == odfUrl) { throw new IllegalArgumentException("odfUrl is null"); }/*from w w w. j a v a 2s . c o m*/ KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); LOG.debug("java version: " + System.getProperty("java.version")); /* * Requires Java 6u10 because of a bug. See also: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582 */ XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); if (false == validity) { LOG.debug("invalid signature"); return null; } // TODO: check what has been signed. X509Certificate signer = keySelector.getCertificate(); if (null == signer) { throw new IllegalStateException("signer X509 certificate is null"); } LOG.debug("signer: " + signer.getSubjectX500Principal()); return signer; }
From source file:cl.nic.dte.util.XMLUtil.java
/** * @see #getCertificate(XMLSignature)/*from w w w . j a v a2 s . c om*/ */ public static X509Certificate getCertificate(cl.sii.siiDte.dsig.SignatureType xml) { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Unmarshal the signature XMLSignature signature; try { signature = fac.unmarshalXMLSignature(new DOMStructure(xml.getDomNode())); } catch (MarshalException e) { return null; } return (getCertificate(signature)); }
From source file:cl.nic.dte.util.XMLUtil.java
/** * @see #getCertificate(XMLSignature)/*w w w . j a va2 s . c o m*/ */ public static X509Certificate getCertificate(cl.sii.siiDte.libroguia.SignatureType xml) { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Unmarshal the signature XMLSignature signature; try { signature = fac.unmarshalXMLSignature(new DOMStructure(xml.getDomNode())); } catch (MarshalException e) { return null; } return (getCertificate(signature)); }
From source file:cl.nic.dte.util.XMLUtil.java
/** * @see #getCertificate(XMLSignature)/* ww w. j av a2 s .com*/ */ public static X509Certificate getCertificate(cl.sii.siiDte.libroboletas.SignatureType xml) { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Unmarshal the signature XMLSignature signature; try { signature = fac.unmarshalXMLSignature(new DOMStructure(xml.getDomNode())); } catch (MarshalException e) { return null; } return (getCertificate(signature)); }
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>// w w w.j a va 2s. 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) */ public static VerifyResult verifySignature(Node xml) { try { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); KeyValueKeySelector ksel = new KeyValueKeySelector(); DOMValidateContext valContext = new DOMValidateContext(ksel, xml); // Unmarshal the signature XMLSignature signature = fac.unmarshalXMLSignature(valContext); 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"))); } return (verifySignature(signature, valContext)); } catch (MarshalException e1) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": " + e1.getMessage())); } }
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 w w . j av a2s . c o 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) */ public static VerifyResult verifySignature(Node xml, Date date) { try { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); KeyValueKeySelector ksel = new KeyValueKeySelector(); DOMValidateContext valContext = new DOMValidateContext(ksel, xml); // Unmarshal the signature XMLSignature signature = fac.unmarshalXMLSignature(valContext); 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"))); } try { // Valida que en la fecha dada el certificado era va'lido x509.checkValidity(date); } catch (CertificateExpiredException e) { String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID"); message = message.replaceAll("%1", DateFormat.getDateInstance().format(date)); message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore())); message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter())); return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message)); } catch (CertificateNotYetValidException e) { String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID"); message = message.replaceAll("%1", DateFormat.getDateInstance().format(date)); message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore())); message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter())); return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message)); } return (verifySignature(signature, valContext)); } catch (MarshalException e1) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": " + e1.getMessage())); } }
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 ww w . ja v a2s. c o m*/ 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; }