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:org.gluu.saml.Response.java
public boolean isValid() throws Exception { NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodes == null || nodes.getLength() == 0) { throw new Exception("Can't find signature in document."); }//from w w w .j a v a 2s . c o m if (setIdAttributeExists()) { tagIdAttributes(xmlDoc); } X509Certificate cert = samlSettings.getCertificate(); DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0)); XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM"); XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx); return xmlSignature.validate(ctx); }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java
/** * Checks whether or not the given Document contains a valid XML Signature * and if it has the exact same content as the original. * // w ww . j a v a 2s . c om * @param cdaFile * @param originalCDA * @return */ public boolean isXMLSignatureValid(Document cdaFile, Document originalCDA) { boolean coreValidity = false; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document checkCDA = db.newDocument(); Node copy = checkCDA.importNode(cdaFile.getDocumentElement(), true); checkCDA.appendChild(copy); if (!isCDAoriginal(checkCDA, originalCDA)) { return false; } // Find Signature element NodeList nl = cdaFile.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { return false; } // Create a DOM XMLSignatureFactory that will be used to unmarshal // the // document containing the XMLSignature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create a DOMValidateContext and specify a KeyValue KeySelector // and document context DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0)); // unmarshal the XMLSignature XMLSignature signature = fac.unmarshalXMLSignature(valContext); // Validate the XMLSignature (generated above) coreValidity = signature.validate(valContext); // Check core validation status if (coreValidity) { return true; } } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); } return coreValidity; }
From source file:org.roda.common.certification.ODFSignatureUtils.java
public static ByteArrayInputStream createSignature(String inputPath, X509Certificate certificate, Key key) { try {// w w w.j ava2 s . c o m ZipFile zipFile = new ZipFile(new File(inputPath)); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Init.init(); XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); DigestMethod digestMethod = factory.newDigestMethod(DigestMethod.SHA1, null); InputStream manifest = zipFile.getInputStream(zipFile.getEntry("META-INF/manifest.xml")); Document docManifest = documentBuilder.parse(manifest); Element rootManifest = docManifest.getDocumentElement(); NodeList listFileEntry = rootManifest.getElementsByTagName("manifest:file-entry"); Document docSignatures; Element rootSignatures; if (zipFile.getEntry(META_INF_DOCUMENTSIGNATURES_XML) != null) { InputStream is = zipFile.getInputStream(zipFile.getEntry(META_INF_DOCUMENTSIGNATURES_XML)); docSignatures = documentBuilder.parse(is); rootSignatures = docSignatures.getDocumentElement(); IOUtils.closeQuietly(is); } else { docSignatures = documentBuilder.newDocument(); rootSignatures = docSignatures.createElement("document-signatures"); rootSignatures.setAttribute("xmlns", OPENOFFICE); docSignatures.appendChild(rootSignatures); Element nodeDocumentSignatures = docManifest.createElement("manifest:file-entry"); nodeDocumentSignatures.setAttribute("manifest:media-type", ""); nodeDocumentSignatures.setAttribute("manifest:full-path", META_INF_DOCUMENTSIGNATURES_XML); rootManifest.appendChild(nodeDocumentSignatures); Element nodeMetaInf = docManifest.createElement("manifest:file-entry"); nodeMetaInf.setAttribute("manifest:media-type", ""); nodeMetaInf.setAttribute("manifest:full-path", "META-INF/"); rootManifest.appendChild(nodeMetaInf); } List<Reference> referenceList = getReferenceList(zipFile, documentBuilder, factory, listFileEntry, digestMethod); digitalSign(factory, referenceList, digestMethod, certificate, docSignatures, rootSignatures, key); ByteArrayOutputStream baos = addSignatureToStream(zipFile, rootManifest, rootSignatures); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); baos.close(); return bais; } catch (Exception e) { LOGGER.debug("ODF signature creation went wrong."); return null; } }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static void verifyCertificates(Path input, Node signatureNode) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException { XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); xmlSignature.getSignatureValue().validate(domValidateContext); // xmlSignature.validate(domValidateContext); KeyInfo keyInfo = xmlSignature.getKeyInfo(); Iterator<?> it = keyInfo.getContent().iterator(); List<X509Certificate> certs = new ArrayList<X509Certificate>(); List<CRL> crls = new ArrayList<CRL>(); while (it.hasNext()) { XMLStructure content = (XMLStructure) it.next(); if (content instanceof X509Data) { X509Data certdata = (X509Data) content; Object[] entries = certdata.getContent().toArray(); for (int i = 0; i < entries.length; i++) { if (entries[i] instanceof X509CRL) { X509CRL crl = (X509CRL) entries[i]; crls.add(crl);/* ww w . j a v a 2 s. c om*/ } if (entries[i] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) entries[i]; cert.checkValidity(); certs.add(cert); } } } } for (CRL c : crls) { for (X509Certificate cert : certs) { if (c.isRevoked(cert)) throw new CertificateRevokedException(null, null, null, null); } } }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
public static ByteArrayInputStream createSignature(String inputPath, X509Certificate certificate, Key key) { try (ZipFile zipFile = new ZipFile(new File(inputPath))) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Init.init();//from w w w.ja v a 2s. c o m XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); DigestMethod digestMethod = factory.newDigestMethod(DigestMethod.SHA1, null); try (InputStream manifest = zipFile.getInputStream(zipFile.getEntry("META-INF/manifest.xml"))) { Document docManifest = documentBuilder.parse(manifest); Element rootManifest = docManifest.getDocumentElement(); NodeList listFileEntry = rootManifest.getElementsByTagName("manifest:file-entry"); Document docSignatures; Element rootSignatures; if (zipFile.getEntry(META_INF_DOCUMENTSIGNATURES_XML) != null) { InputStream is = zipFile.getInputStream(zipFile.getEntry(META_INF_DOCUMENTSIGNATURES_XML)); docSignatures = documentBuilder.parse(is); rootSignatures = docSignatures.getDocumentElement(); IOUtils.closeQuietly(is); } else { docSignatures = documentBuilder.newDocument(); rootSignatures = docSignatures.createElement("document-signatures"); rootSignatures.setAttribute("xmlns", OPENOFFICE); docSignatures.appendChild(rootSignatures); Element nodeDocumentSignatures = docManifest.createElement("manifest:file-entry"); nodeDocumentSignatures.setAttribute("manifest:media-type", ""); nodeDocumentSignatures.setAttribute("manifest:full-path", META_INF_DOCUMENTSIGNATURES_XML); rootManifest.appendChild(nodeDocumentSignatures); Element nodeMetaInf = docManifest.createElement("manifest:file-entry"); nodeMetaInf.setAttribute("manifest:media-type", ""); nodeMetaInf.setAttribute("manifest:full-path", "META-INF/"); rootManifest.appendChild(nodeMetaInf); } List<Reference> referenceList = getReferenceList(zipFile, documentBuilder, factory, listFileEntry, digestMethod); digitalSign(factory, referenceList, digestMethod, certificate, docSignatures, rootSignatures, key); ByteArrayOutputStream baos = addSignatureToStream(zipFile, rootManifest, rootSignatures); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); baos.close(); return bais; } } catch (Exception e) { LOGGER.debug("ODF signature creation went wrong."); } return null; }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static void verifyCertificates(Node signatureNode) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException { XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); xmlSignature.getSignatureValue().validate(domValidateContext); // xmlSignature.validate(domValidateContext); KeyInfo keyInfo = xmlSignature.getKeyInfo(); Iterator<?> it = keyInfo.getContent().iterator(); List<X509Certificate> certs = new ArrayList<>(); List<CRL> crls = new ArrayList<>(); while (it.hasNext()) { XMLStructure content = (XMLStructure) it.next(); if (content instanceof X509Data) { X509Data certdata = (X509Data) content; Object[] entries = certdata.getContent().toArray(); for (int i = 0; i < entries.length; i++) { if (entries[i] instanceof X509CRL) { X509CRL crl = (X509CRL) entries[i]; crls.add(crl);/*from ww w.j ava 2 s . co m*/ } if (entries[i] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) entries[i]; cert.checkValidity(); certs.add(cert); } } } } for (CRL c : crls) { for (X509Certificate cert : certs) { if (c.isRevoked(cert)) throw new CertificateRevokedException(null, null, null, null); } } }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Sign the payloadBody as-is. Note that this is going to be encrypted anyway * so we avoid any incompatibilities due to canonicalisation, and we don't * care if the payloadBody is text, compressed and so on. Re-writes payloadBody * with a serialised XML Digital Signature "Signature" element containing an * enveloping signature, or throws an exception to signal failure. * /* w w w . j a v a2s . c om*/ * @param pk * @param cert * @throws Exception */ private void signPayload(PrivateKey pk, X509Certificate cert) throws Exception { if ((pk == null) || (cert == null)) { throw new Exception("Null signing material"); } cert.checkValidity(); XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; String objectRef = "uuid" + UUID.randomUUID().toString(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = null; DOMStructure payloadContent = null; if (compressed || base64 || !mimeType.contains("xml")) { ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null)); doc = dbf.newDocumentBuilder().newDocument(); payloadContent = new DOMStructure(doc.createTextNode(payloadBody)); } else { Transform t = xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null); ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(t), null, null); doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(payloadBody))); payloadContent = new DOMStructure(doc.getDocumentElement()); } XMLObject payloadObject = xsf.newXMLObject(Collections.singletonList(payloadContent), objectRef, null, null); SignedInfo si = xsf.newSignedInfo( xsf.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = xsf.getKeyInfoFactory(); ArrayList<Object> x509content = new ArrayList<Object>(); x509content.add(cert); X509Data xd = kif.newX509Data(x509content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = xsf.newXMLSignature(si, ki, Collections.singletonList(payloadObject), null, null); DOMSignContext dsc = new DOMSignContext(pk, doc); signature.sign(dsc); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); Transformer tx = TransformerFactory.newInstance().newTransformer(); tx.transform(new DOMSource(doc), sr); if (sw.toString().indexOf("<?xml ") == 0) { payloadBody = sw.toString().substring(sw.toString().indexOf("?>") + "?>".length()); } else { payloadBody = sw.toString(); } }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Carries out the cryptographic part of signature verification on a parsed * "Signature" element.//w ww. j av a 2s . co m * @param signature * @throws Exception */ private void verifySignature(Element signature) throws Exception { X509Certificate x509 = getCertificate(signature); SimpleKeySelector sks = new SimpleKeySelector(); sks.setFixedKey(x509.getPublicKey()); DOMStructure sig = new DOMStructure(signature); XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM"); DOMValidateContext dvc = new DOMValidateContext(sks, signature); dvc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); XMLSignature xmlsig = xsf.unmarshalXMLSignature(sig); boolean isvalid = xmlsig.validate(dvc); if (!isvalid) { throw new Exception("Signature invalid"); } }
From source file:test.be.fedict.eid.dss.DigitalSignatureServiceTest.java
private void signDocument(Document document) throws IOException, PKCS11Exception, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, CardException { Messages messages = new Messages(Locale.getDefault()); PcscEid pcscEid = new PcscEid(new TestView(), messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID..."); pcscEid.waitForEidPresent();/*w w w . j a v a2s . c om*/ } // PrivateKeyEntry privateKeyEntry = pcscEid.getPrivateKeyEntry(); PrivateKeyEntry privateKeyEntry = null; // TODO: refactor once Commons eID has been released. XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignContext signContext = new DOMSignContext(privateKeyEntry.getPrivateKey(), document.getDocumentElement()); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference("#id", digestMethod); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); X509Certificate signingCertificate = (X509Certificate) privateKeyEntry.getCertificate(); x509DataObjects.add(signingCertificate); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); List<Object> keyInfoContent = new LinkedList<Object>(); keyInfoContent.add(x509Data); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(signContext); pcscEid.close(); }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private void addSignature(Element wsSecurityHeaderElement, Element tsElement, Element bodyElement) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, NoSuchProviderException, SOAPException { if (null == this.privateKey) { return;//from ww w . ja va 2 s.c o m } DOMSignContext domSignContext = new DOMSignContext(this.privateKey, wsSecurityHeaderElement); domSignContext.setDefaultNamespacePrefix("ds"); domSignContext.setIdAttributeNS(tsElement, WSU_NAMESPACE, "Id"); domSignContext.setIdAttributeNS(bodyElement, WSU_NAMESPACE, "Id"); LOG.debug("Timestamp element found: " + (null != domSignContext.getElementById("TS"))); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); List<Reference> references = new LinkedList<Reference>(); List<String> tsPrefixes = new LinkedList<String>(); tsPrefixes.add("wsse"); tsPrefixes.add("S"); ExcC14NParameterSpec tsTransformSpec = new ExcC14NParameterSpec(tsPrefixes); Reference tsReference = xmlSignatureFactory.newReference("#TS", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null), Collections.singletonList( xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, tsTransformSpec)), null, null); references.add(tsReference); if (this.signBody) { List<String> bodyPrefixes = new LinkedList<String>(); ExcC14NParameterSpec bodyTransformSpec = new ExcC14NParameterSpec(bodyPrefixes); Reference bodyReference = xmlSignatureFactory.newReference("#Body", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null), Collections.singletonList( xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, bodyTransformSpec)), null, null); references.add(bodyReference); } if (this.signBinarySecurityToken) { Reference bstReference = xmlSignatureFactory .newReference("#X509", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null), Collections.singletonList(xmlSignatureFactory .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null); references.add(bstReference); } SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(this.signatureAlgorithm, null), references); KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); Document document = wsSecurityHeaderElement.getOwnerDocument(); Element securityTokenReferenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:SecurityTokenReference"); Element referenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:Reference"); referenceElement.setAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"); referenceElement.setAttribute("URI", "#X509"); securityTokenReferenceElement.appendChild(referenceElement); KeyInfo keyInfo = keyInfoFactory .newKeyInfo(Collections.singletonList(new DOMStructure(securityTokenReferenceElement))); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, null, "SIG", null); xmlSignature.sign(domSignContext); }