List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newXMLSignature
public abstract XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki);
XMLSignature
and initializes it with the contents of the specified SignedInfo
and KeyInfo
objects. From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Method used to create an enveloped digital signature for an element of a TAXII document. * * @param element the element to be signed * @param keyEntry the PrivateKeyEntry/*w w w . ja v a 2 s . c o m*/ * @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element * @return the status of the operation * * Usage Example: * String pks = config.getProperty("pathToPublisherKeyStore"); * String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword")); * String keyName = config.getProperty("publisherKeyName"); * String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword")); * PrivateKeyEntry keyEntry = FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW); * List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1); */ private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) { element.normalize(); boolean status = false; //Create XML Signature Factory XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM"); PublicKey publicKey = ClientUtil.getPublicKey(keyEntry); PrivateKey privateKey = keyEntry.getPrivateKey(); DOMSignContext dsc = new DOMSignContext(privateKey, element); dsc.setDefaultNamespacePrefix("ds"); dsc.setURIDereferencer(new MyURIDereferencer(element)); SignedInfo si = null; DigestMethod dm = null; SignatureMethod sm = null; KeyInfo ki = null; X509Data xd; List<Serializable> x509Content = new ArrayList<>(); try { String algorithm = publicKey.getAlgorithm(); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); String algorithmName = cert.getSigAlgName(); if (algorithm.toUpperCase().contains("RSA")) { if (algorithmName.toUpperCase().contains("SHA1")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null); sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } else if (algorithmName.toUpperCase().contains("SHA2")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null); sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } CanonicalizationMethod cm; if (cbIndex != -1) { cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex + "]/*[local-name()='Content'][1]/*)"; List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } else { List<Transform> transforms = new ArrayList<>(2); transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); String refUri = "#xpointer(/*)"; List<Reference> references = Collections .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory(); xd = kif.newX509Data(x509Content); ki = kif.newKeyInfo(Collections.singletonList(xd)); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } } catch (NoSuchAlgorithmException ex) { logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document."); } catch (InvalidAlgorithmParameterException ex) { logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document."); } // Create a new XML Signature XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki); try { // Sign the document signature.sign(dsc); status = true; } catch (MarshalException ex) { logger.error("MarshalException when attempting to digitally sign a document."); } catch (XMLSignatureException ex) { logger.error("XMLSignature Exception when attempting to digitally sign a document."); } catch (Exception e) { logger.error("General exception when attempting to digitally sign a document."); } return status; }
From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java
private void signXML(Element target, String refId, KeyStoreInfo keyStoreInfo) { org.apache.xml.security.Init.init(); XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(SIGN_FACTORY_TYPE); try {/*from w w w . jav a2 s.c o m*/ DigestMethod method = signFactory.newDigestMethod(DigestMethod.SHA1, null); Transform transform = signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null); Reference ref = signFactory.newReference('#' + refId, method, Collections.singletonList(transform), null, null); CanonicalizationMethod canonMethod = signFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signMethod = signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); SignedInfo si = signFactory.newSignedInfo(canonMethod, signMethod, Collections.singletonList(ref)); KeyStore.PrivateKeyEntry keyEntry = getKeyEntry(keyStoreInfo); if (keyEntry == null) { throw new IllegalStateException("Key is not found in keystore. Alias: " + keyStoreInfo.getAlias()); } KeyInfo ki = getKeyInfo(signFactory, keyEntry); DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), target); XMLSignature signature = signFactory.newXMLSignature(si, ki); signature.sign(dsc); } catch (Exception e) { throw new STSException("Cannot sign xml document: " + e.getMessage(), e); } }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) { XMLSignatureFactory fac = initXMLSigFactory(); X509Certificate cert = (X509Certificate) origCert; // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List<Object> x509Content = null;//new ArrayList<Object>(); List<X509Data> data = new ArrayList<X509Data>(); if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN)) { x509Content = new ArrayList<Object>(); x509Content.add(cert.getSubjectDN().getName()); // x509Content.add(cert); //x509Content.add(cert.getSubjectDN().getName()); X509Data xd = kif.newX509Data(x509Content); data.add(xd);/* w w w. j a va2s .co m*/ } // if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_X500_PRINICPAL)) { // } if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_BASE64)) { x509Content = new ArrayList<Object>(); x509Content.add(cert); //x509Content.add(cert.getSubjectX500Principal().getName()); X509Data xd = kif.newX509Data(x509Content); data.add(xd); } if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SERIAL)) { x509Content = new ArrayList<Object>(); X509IssuerSerial issuer = kif.newX509IssuerSerial(cert.getIssuerX500Principal().getName(), cert.getSerialNumber()); x509Content.add(issuer); X509Data xd = kif.newX509Data(x509Content); data.add(xd); } // //x509Content.add(cert); KeyInfo ki = kif.newKeyInfo(data); // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privateKey, node); dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2"); // Create the XMLSignature, but don't sign it yet. try { SignedInfo si = initSignedInfo(fac); XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate, and sign the enveloped signature. signature.sign(dsc); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias, String keyPassword) {/*from w w w . ja v a 2 s . co m*/ 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 ww.j a v a2 s . 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 w w w. j av a2s . c o 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 a va 2s . com * @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 *///from ww w .j av a 2 s. co 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 ava 2 s . 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: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 ww. ja v a 2 s . c o 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; }