List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newDigestMethod
public abstract DigestMethod newDigestMethod(String algorithm, DigestMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;
DigestMethod
for the specified algorithm URI and parameters. From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
public String getSignedMessage(SignatureHelper signatureHelper) { if (_responseDocument == null) { try {// w ww . jav a 2s. com _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true); } catch (OAException | XMLStreamException e) { _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e); return null; } } signatureHelper.tagIdAttributes(_responseDocument); KeyPair keypair = signatureHelper.getKeyPairFromKeystore(); // Set signing context with PrivateKey and root of the Document DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), _responseDocument.getDocumentElement()); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; SignedInfo si = null; XMLSignature signature = null; try { // Create reference for "" -> root of the document // SAML requires enveloped transform List<Transform> transformsList = new ArrayList<>(); transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null)); ref = fac.newReference("#" + getId(), fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) // .. some selection here; nothing fancy, just trying to switch based on signing key format String sigMethod; String keyAlg = keypair.getPrivate().getAlgorithm(); if (keyAlg.contains("RSA")) { sigMethod = SignatureMethod.RSA_SHA1; } else if (keyAlg.contains("DSA")) { sigMethod = SignatureMethod.DSA_SHA1; } else { _logger.error("Unknown signing key algorithm: {}", keyAlg); return null; } si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigMethod, null), Collections.singletonList(ref)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); signature = fac.newXMLSignature(si, ki); // Sign! signature.sign(dsc); String s = XMLUtils.getStringFromDocument(_responseDocument); _logger.info("Document after signing whole message:\n{}", s); return s; } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { _logger.error("Could not create reference to signable content: {}", e.getMessage(), e); return null; } catch (KeyException e) { _logger.error("Could not establish key info: {}", e.getMessage(), e); return null; } catch (MarshalException | XMLSignatureException e) { _logger.error("Error signing document: {}", e.getMessage(), e); return null; } catch (OAException e) { _logger.error("Error creating string from XML document: {}", e.getMessage(), e); return null; } }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
/** * Requires the responseDocument to be already initialized, just adding another * Signature section to the existing documnet * @param signatureHelper//from www . j a va 2 s. com * @return */ public String getMessageWithSignedAssertion(SignatureHelper signatureHelper) { if (_responseDocument == null) { try { _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true); } catch (OAException | XMLStreamException e) { _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e); return null; } } KeyPair keypair = signatureHelper.getKeyPairFromKeystore(); // Set signing context with PrivateKey and root of the Document Node localRoot = _assertion.getAssertionNode(); signatureHelper.tagIdAttributes(localRoot.getOwnerDocument()); DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), localRoot); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference refAssertion = null; SignedInfo si = null; XMLSignature signature = null; try { // Create reference for "" -> Assertion in the document // SAML requires enveloped transform List<Transform> transformsList = new ArrayList<>(); transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null)); refAssertion = fac.newReference("#" + getAssertion().getId(), fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) // .. some selection here; nothing fancy, just trying to switch based on signing key format String sigMethod; String keyAlg = keypair.getPrivate().getAlgorithm(); if (keyAlg.contains("RSA")) { sigMethod = SignatureMethod.RSA_SHA1; } else if (keyAlg.contains("DSA")) { sigMethod = SignatureMethod.DSA_SHA1; } else { _logger.error("Unknown signing key algorithm: {}", keyAlg); return null; } si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigMethod, null), Collections.singletonList(refAssertion)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); signature = fac.newXMLSignature(si, ki); // before: _logger.info("Signing assertion in document"); // _logger.info("Document to sign:\n{}", XMLUtils.getStringFromDocument(localRoot.getOwnerDocument())); // Sign! signature.sign(dsc); return XMLUtils.getStringFromDocument(localRoot.getOwnerDocument()); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { _logger.error("Could not create reference to signable content: {}", e.getMessage(), e); return null; } catch (KeyException e) { _logger.error("Could not establish key info: {}", e.getMessage(), e); return null; } catch (MarshalException | XMLSignatureException e) { _logger.error("Error signing document: {}", e.getMessage(), e); return null; } catch (OAException e) { _logger.error("Error creating string from XML document: {}", e.getMessage(), e); return null; } }
From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
/** * This will sign a SAMLR2 Identity artifact (assertion, request or response) represeted as a DOM tree * The signature will be inserted as the first child of the root element. * * @param doc/* ww w. ja v a 2 s. c om*/ * @param id * @return */ protected Document sign(Document doc, String id) throws SamlR2SignatureException { try { Certificate cert = keyResolver.getCertificate(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider); if (logger.isDebugEnabled()) logger.debug("Creating XML DOM Digital Siganture (not signing yet!)"); // Create a Reference to the enveloped document and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. // The URI must be the assertion ID List<Transform> transforms = new ArrayList<Transform>(); transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // Magically, this solves assertion DS validation when embedded in a signed response :) transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); // Use signature method based on key algorithm. String signatureMethod = SignatureMethod.DSA_SHA1; if (keyResolver.getPrivateKey().getAlgorithm().equals("RSA")) signatureMethod = SignatureMethod.RSA_SHA1; logger.debug("Using signature method " + signatureMethod); // Create the SignedInfo, with the X509 Certificate /* SignedInfo si = fac.newSignedInfo (fac.newCanonicalizationMethod (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); */ SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); // Create a KeyInfo and add the Certificate to it KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); //KeyValue kv = kif.newKeyValue(keyResolver.getCertificate().getPublicKey()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); if (logger.isDebugEnabled()) logger.debug("Signing SAMLR2 Identity Artifact ..."); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(keyResolver.getPrivateKey(), doc.getDocumentElement(), doc.getDocumentElement().getFirstChild()); // Sign the assertion signature.sign(dsc); if (logger.isDebugEnabled()) logger.debug("Signing SAMLR2 Identity Artifact ... DONE!"); return doc; } catch (NoSuchAlgorithmException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (XMLSignatureException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (MarshalException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (SSOKeyResolverException e) { throw new SamlR2SignatureException(e.getMessage(), e); } }
From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java
/** * Sign a simple DOM document using the configured JSR 105 Provider */// w w w. j ava 2 s . c o m @Test public void simpleDocumentSign() throws Exception { //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "src/test/resources/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("target/signature.xml"); KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); //load the keystore ks.load(fis, keystorePass.toCharArray()); //get the private key for signing. PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); PublicKey publicKey = cert.getPublicKey(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference("#12345", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Instantiate the document to be signed javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); //Build a sample document. It will look something like: //<!-- Comment before --> //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text //</apache:RootElement> //<!-- Comment after --> doc.appendChild(doc.createComment(" Comment before ")); Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement"); root.setAttributeNS(null, "ID", "12345"); root.setAttributeNS(null, "attr1", "test1"); root.setAttributeNS(null, "attr2", "test2"); root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo", "http://example.org/#foo"); root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test"); root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1"); doc.appendChild(root); root.appendChild(doc.createTextNode("Some simple text\n")); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement()); // Create the XMLSignature (but don't sign it yet) KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); // TODO : Verify signature ? // output the resulting document FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); }
From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java
/** * Sign a SAMLR2 Assertion using the configured JSR 105 Provider *//*from ww w.j a v a 2s. c om*/ @Test public void assertionSign() throws Exception { //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "src/test/resources/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File assertionFile = new File("src/test/resources/assertion-001.xml"); File signatureFile = new File("target/assertion-signed-001.xml"); JAXBContext context = JAXBContext.newInstance("oasis.names.tc.saml._2_0.assertion"); Unmarshaller um = context.createUnmarshaller(); JAXBElement jaxbElement = (JAXBElement) um.unmarshal(assertionFile); AssertionType assertion = (AssertionType) jaxbElement.getValue(); // Unmarshall the assertion KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); //load the keystore ks.load(fis, keystorePass.toCharArray()); //get the private key for signing. PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); PublicKey publicKey = cert.getPublicKey(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference("#" + assertion.getID(), fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Instantiate the document to be signed javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); Marshaller m = context.createMarshaller(); m.marshal(jaxbElement, doc); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement(), doc.getDocumentElement().getFirstChild()); // Create the XMLSignature (but don't sign it yet) KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); // output the resulting document FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); }
From source file:org.roda.common.certification.ODFSignatureUtils.java
public static ByteArrayInputStream createSignature(String inputPath, X509Certificate certificate, Key key) { try {//from w w w . j a va 2 s.c om 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.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 ww w.j av a 2 s. co 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.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. * /*from w w w. j a va2s. com*/ * @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:test.be.fedict.eid.applet.model.XmlSignatureServiceBean.java
private byte[] getXmlSignatureDigestValue(String digestAlgo, List<DigestInfo> digestInfos, HttpSession httpSession) throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerFactoryConfigurationError, TransformerException, MalformedURLException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); Key key = new Key() { private static final long serialVersionUID = 1L; public String getAlgorithm() { return null; }/*from w w w. j a v a2s . co m*/ public byte[] getEncoded() { return null; } public String getFormat() { return null; } }; XMLSignContext signContext = new DOMSignContext(key, document); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); List<Reference> references = new LinkedList<Reference>(); for (DigestInfo digestInfo : digestInfos) { byte[] documentDigestValue = digestInfo.digestValue; DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo), null); String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile()); Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null, documentDigestValue); references.add(reference); } SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null); DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature; domXmlSignature.marshal(document, "ds", (DOMCryptoContext) signContext); Source source = new DOMSource(document); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); xformer.transform(source, result); String documentStr = stringWriter.getBuffer().toString(); httpSession.setAttribute("xmlDocument", documentStr); DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo; ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); domSignedInfo.canonicalize(signContext, dataStream); byte[] octets = dataStream.toByteArray(); MessageDigest jcaMessageDigest = MessageDigest.getInstance(digestAlgo); byte[] digestValue = jcaMessageDigest.digest(octets); return digestValue; }
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 ww . j av a 2s .co m*/ } // 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(); }