List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newTransform
public abstract Transform newTransform(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;
Transform
for the specified algorithm URI and parameters. From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private Reference initReference(XMLSignatureFactory fac) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { List transformers = new ArrayList(); transformers.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); String dm = map.getProperty(SIGNATURE_OPTION_DIGEST_METHOD); if (dm == null) { dm = DigestMethod.SHA1;/*from w ww . ja v a2 s . c o m*/ } Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null); return ref; }
From source file:org.apache.ws.security.message.WSSecSignatureBase.java
/** * This method adds references to the Signature. * /*from w w w . j ava2 s .c o m*/ * @param doc The parent document * @param references The list of references to sign * @param wsDocInfo The WSDocInfo object to store protection elements in * @param signatureFactory The XMLSignature object * @param secHeader The Security Header * @param wssConfig The WSSConfig * @param digestAlgo The digest algorithm to use * @throws WSSecurityException */ public List<javax.xml.crypto.dsig.Reference> addReferencesToSign(Document doc, List<WSEncryptionPart> references, WSDocInfo wsDocInfo, XMLSignatureFactory signatureFactory, WSSecHeader secHeader, WSSConfig wssConfig, String digestAlgo) throws WSSecurityException { DigestMethod digestMethod; try { digestMethod = signatureFactory.newDigestMethod(digestAlgo, null); } catch (Exception ex) { log.error("", ex); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex); } List<javax.xml.crypto.dsig.Reference> referenceList = new ArrayList<javax.xml.crypto.dsig.Reference>(); for (WSEncryptionPart encPart : references) { String idToSign = encPart.getId(); String elemName = encPart.getName(); Element element = encPart.getElement(); // // Set up the elements to sign. There is one reserved element // names: "STRTransform": Setup the ds:Reference to use STR Transform // try { if (idToSign != null) { Transform transform = null; if ("STRTransform".equals(elemName)) { Element ctx = createSTRParameter(doc); XMLStructure structure = new DOMStructure(ctx); transform = signatureFactory.newTransform(STRTransform.TRANSFORM_URI, structure); } else { TransformParameterSpec transformSpec = null; if (element == null) { if (callbackLookup == null) { callbackLookup = new DOMCallbackLookup(doc); } element = callbackLookup.getElement(idToSign, null, false); } if (wssConfig.isWsiBSPCompliant()) { List<String> prefixes = getInclusivePrefixes(element); transformSpec = new ExcC14NParameterSpec(prefixes); } transform = signatureFactory.newTransform(WSConstants.C14N_EXCL_OMIT_COMMENTS, transformSpec); } if (element != null) { wsDocInfo.addTokenElement(element, false); } javax.xml.crypto.dsig.Reference reference = signatureFactory.newReference("#" + idToSign, digestMethod, Collections.singletonList(transform), null, null); referenceList.add(reference); } else { String nmSpace = encPart.getNamespace(); List<Element> elementsToSign = null; if (element != null) { elementsToSign = Collections.singletonList(element); } else { if (callbackLookup == null) { callbackLookup = new DOMCallbackLookup(doc); } elementsToSign = WSSecurityUtil.findElements(encPart, callbackLookup, doc); } if (elementsToSign == null || elementsToSign.size() == 0) { throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement", new Object[] { nmSpace + ", " + elemName }); } for (Element elementToSign : elementsToSign) { TransformParameterSpec transformSpec = null; if (wssConfig.isWsiBSPCompliant()) { List<String> prefixes = getInclusivePrefixes(elementToSign); transformSpec = new ExcC14NParameterSpec(prefixes); } Transform transform = signatureFactory.newTransform(WSConstants.C14N_EXCL_OMIT_COMMENTS, transformSpec); javax.xml.crypto.dsig.Reference reference = signatureFactory.newReference( "#" + setWsuId(elementToSign), digestMethod, Collections.singletonList(transform), null, null); referenceList.add(reference); wsDocInfo.addTokenElement(elementToSign, false); } } } catch (Exception ex) { log.error("", ex); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex); } } return referenceList; }
From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias, String keyPassword) {// w w w . j a v a 2 s .c om DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder; Document doc; try { builder = dbf.newDocumentBuilder(); doc = builder.parse(new InputSource(new ByteArrayInputStream(getRequest(plain).getBytes("utf-8")))); // Prepare doc by marking attributes as referenceable: tagIdAttributes(doc); // Prepare cryptographic environemnt KeyStore keystore = getKeystore("JKS", keystoreStream, keystorePassword); if (keystore == null) return null; KeyPair kp; kp = getKeyPairFromKeystore(keystore, keyAlias, keyPassword); if (kp == null) { // Generate key, to prove that it works... KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(512); kp = kpg.generateKeyPair(); } // Set signing context with PrivateKey and root of the Document DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Create reference for "" -> root of the document // SAML requires enveloped transform Reference ref = fac.newReference("#" + this._id, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(kp.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature signature = fac.newXMLSignature(si, ki); String before = docToString(doc); // Sign! signature.sign(dsc); _authnRequestDocument = doc; // persist, as we've worked hard for it String after = docToString(doc); if (_logger.isDebugEnabled()) { _logger.debug("Before: {}", before); _logger.debug("After : {}", after); } return after; } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // key generation exception e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { // digest algorithm selection exception e.printStackTrace(); } catch (KeyException e) { // when key-value was not available (when adding to KeyInfo) e.printStackTrace(); } catch (MarshalException e) { // sign didn't work: e.printStackTrace(); } catch (XMLSignatureException e) { // sign didn't work: e.printStackTrace(); } return null; }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
public String getSignedMessage(SignatureHelper signatureHelper) { if (_responseDocument == null) { try {/* w w w . ja va 2s . c o m*/ _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 w ww . j a v a2s. co m*/ * @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//from w w w .j av a 2s .c o m * @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 ww . j a va 2s .c om*/ @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 w w w . j av a 2 s . com*/ @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
private static List<Reference> getReferenceList(ZipFile zipFile, DocumentBuilder documentBuilder, XMLSignatureFactory factory, NodeList listFileEntry, DigestMethod digestMethod) throws Exception { Transform transform = factory.newTransform(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, (TransformParameterSpec) null); List<Transform> transformList = new ArrayList<Transform>(); transformList.add(transform);/* w w w. j av a2 s . com*/ MessageDigest messageDigest = MessageDigest.getInstance(RodaConstants.SHA1); List<Reference> referenceList = new ArrayList<Reference>(); for (int i = 0; i < listFileEntry.getLength(); i++) { String fullPath = ((Element) listFileEntry.item(i)).getAttribute("manifest:full-path"); Reference reference; if (!fullPath.endsWith("/") && !fullPath.equals(META_INF_DOCUMENTSIGNATURES_XML)) { if (fullPath.equals("content.xml") || fullPath.equals("meta.xml") || fullPath.equals("styles.xml") || fullPath.equals("settings.xml")) { InputStream xmlFile = zipFile.getInputStream(zipFile.getEntry(fullPath)); Element root = documentBuilder.parse(xmlFile).getDocumentElement(); IOUtils.closeQuietly(xmlFile); Canonicalizer canonicalizer = Canonicalizer .getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); byte[] docCanonicalize = canonicalizer.canonicalizeSubtree(root); byte[] digestValue = messageDigest.digest(docCanonicalize); reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, transformList, null, null, digestValue); } else { InputStream is = zipFile.getInputStream(zipFile.getEntry(fullPath)); byte[] digestValue = messageDigest.digest(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, null, null, null, digestValue); } referenceList.add(reference); } } return referenceList; }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static List<Reference> getReferenceList(ZipFile zipFile, DocumentBuilder documentBuilder, XMLSignatureFactory factory, NodeList listFileEntry, DigestMethod digestMethod) throws IOException, SAXException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CanonicalizationException, InvalidCanonicalizerException { Transform transform = factory.newTransform(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, (TransformParameterSpec) null); List<Transform> transformList = new ArrayList<>(); transformList.add(transform);//w w w .j av a 2 s . co m MessageDigest messageDigest = MessageDigest.getInstance(RodaConstants.SHA1); List<Reference> referenceList = new ArrayList<>(); for (int i = 0; i < listFileEntry.getLength(); i++) { String fullPath = ((Element) listFileEntry.item(i)).getAttribute("manifest:full-path"); Reference reference; if (!fullPath.endsWith("/") && !fullPath.equals(META_INF_DOCUMENTSIGNATURES_XML)) { if ("content.xml".equals(fullPath) || "meta.xml".equals(fullPath) || "styles.xml".equals(fullPath) || "settings.xml".equals(fullPath)) { try (InputStream xmlFile = zipFile.getInputStream(zipFile.getEntry(fullPath))) { Element root = documentBuilder.parse(xmlFile).getDocumentElement(); Canonicalizer canonicalizer = Canonicalizer .getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); byte[] docCanonicalize = canonicalizer.canonicalizeSubtree(root); byte[] digestValue = messageDigest.digest(docCanonicalize); reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, transformList, null, null, digestValue); } } else { try (InputStream is = zipFile.getInputStream(zipFile.getEntry(fullPath))) { byte[] digestValue = messageDigest.digest(IOUtils.toByteArray(is)); reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, null, null, null, digestValue); } } referenceList.add(reference); } } return referenceList; }