List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory getInstance
public static XMLSignatureFactory getInstance(String mechanismType)
XMLSignatureFactory
that supports the specified XML processing mechanism and representation type (ex: "DOM"). From source file:cl.nic.dte.util.XMLUtil.java
/** * @see #getCertificate(XMLSignature)//from w w w. ja v a 2s . co m */ 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 v a2 s. co 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:com.helger.peppol.httpclient.SMPHttpResponseHandlerSigned.java
private static boolean _checkSignature(@Nonnull @WillClose final InputStream aEntityInputStream) throws Exception { try {/*from ww w . j a va 2s .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
/** * @see #getCertificate(XMLSignature)// w ww .j a va 2 s. c om */ 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: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 v a2s . com*/ 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:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java
/** * Load a trusted list for the specified URL * * @param url//from w w w . j a va 2 s.c om * @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:no.difi.sdp.client.asice.signature.CreateSignatureTest.java
private boolean verify_signature(final Signature signature2) { try {// www .j av a2 s .c om 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: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.j a v a 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, 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:com.alvexcore.repo.SimpleKeySelectorResult.java
private LicenseInfo getLicenseInfo(InputStream lic) { Document licenseXML = null;/*from w w w . ja v a 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: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 ww w .j a va2 s. 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) { 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())); } }