List of usage examples for javax.xml.crypto.dsig.dom DOMSignContext putNamespacePrefix
public String putNamespacePrefix(String namespaceURI, String prefix)
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/*from ww w.ja v a2s . c o m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
@Override public byte[] getArchiveTimestampData(int index, Document originalData) throws IOException { try {//ww w . j av a 2s . c o m ByteArrayOutputStream buffer = new ByteArrayOutputStream(); XMLStructure s = new DOMStructure(signatureElement); XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); DOMXMLSignature signature = (DOMXMLSignature) factory.unmarshalXMLSignature(s); DOMSignContext signContext = new DOMSignContext(new SpecialPrivateKey(), signatureElement); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); signContext.setProperty("javax.xml.crypto.dsig.cacheReference", true); signContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", originalData)); // TODO naramsda: check ! Don't let met publish that without further test !! // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // dbf.setNamespaceAware(true); // org.w3c.dom.Document xmlDoc = dbf.newDocumentBuilder().newDocument(); // signature.marshal(xmlDoc.createElement("test"), "ds", signContext); for (Object o : signature.getSignedInfo().getReferences()) { DOMReference r = (DOMReference) o; InputStream data = r.getDigestInputStream(); if (data != null) { IOUtils.copy(data, buffer); } } List<Node> timeStampNodesXadesA = new LinkedList<Node>(); Element signedInfo = XMLUtils.getElement(signatureElement, "./ds:SignedInfo"); timeStampNodesXadesA.add(signedInfo); Element signatureValue = XMLUtils.getElement(signatureElement, "./ds:SignatureValue"); timeStampNodesXadesA.add(signatureValue); Element keyInfo = XMLUtils.getElement(signatureElement, "./ds:KeyInfo"); timeStampNodesXadesA.add(keyInfo); Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement); NodeList unsignedProperties = unsignedSignaturePropertiesNode.getChildNodes(); int count = 0; for (int i = 0; i < unsignedProperties.getLength(); i++) { if (unsignedProperties.item(i).getNodeType() == Node.ELEMENT_NODE) { Element unsignedProperty = (Element) unsignedProperties.item(i); if ("ArchiveTimeStamp".equals(unsignedProperty.getLocalName())) { if (count == index) { LOG.info("We only need data up to ArchiveTimeStamp index " + index); break; } count++; } timeStampNodesXadesA.add(unsignedProperty); } } buffer.write(getC14nValue(timeStampNodesXadesA)); return buffer.toByteArray(); // } catch (ParserConfigurationException e) { // throw new IOException("Error when computing the archive data", e); } catch (MarshalException e) { throw new IOException("Error when computing the archive data", e); } catch (XPathExpressionException e) { throw new EncodingException(MSG.ARCHIVE_TIMESTAMP_DATA_ENCODING); } }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
protected InputStream getToBeSignedStream(Document document, SignatureParameters parameters) { try {// www . ja v a 2 s.c o m /* Read the document */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = null; if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) { doc = db.parse(document.openStream()); } else { doc = db.newDocument(); doc.appendChild(doc.createElement("empty")); } /* Interceptor */ SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey(); /* Context */ DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement()); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); String signatureValueId = "value-" + computeDeterministicId(parameters); DOMXMLSignature signature = createSignature(parameters, doc, document, signContext, signatureValueId); /* Output document */ if (LOG.isLoggable(Level.FINE)) { ByteArrayOutputStream logOutput = new ByteArrayOutputStream(); Result result = new StreamResult(logOutput); Transformer xformer = TransformerFactory.newInstance().newTransformer(); Source source = new DOMSource(doc); xformer.transform(source, result); LOG.fine("Document after digest " + new String(logOutput.toByteArray())); } DOMSignedInfo domSignedInfo = (DOMSignedInfo) signature.getSignedInfo(); ByteArrayOutputStream output = new ByteArrayOutputStream(); domSignedInfo.canonicalize(signContext, output); output.close(); return new ByteArrayInputStream(output.toByteArray()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java
Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue) { try {/*from w w w. j a v a2s.c om*/ /* Read the document */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = null; if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) { doc = db.parse(document.openStream()); } else { doc = db.newDocument(); doc.appendChild(doc.createElement("empty")); } /* Interceptor */ SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey(); /* Context */ DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement()); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); String signatureValueId = "value-" + computeDeterministicId(parameters); DOMXMLSignature domSig = createSignature(parameters, doc, document, signContext, signatureValueId); String xpathString = "//ds:SignatureValue[@Id='" + signatureValueId + "']"; Element signatureValueEl = XMLUtils.getElement(doc, xpathString); if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.ECDSA) { signatureValueEl.setTextContent( new String(Base64.encode(SignatureECDSA.convertASN1toXMLDSIG(signatureValue)))); } else if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.DSA) { signatureValueEl.setTextContent(new String(Base64.encode(convertASN1toXMLDSIG(signatureValue)))); } else { signatureValueEl.setTextContent(new String(Base64.encode(signatureValue))); } UnsignedPropertiesType unsigned = createUnsignedXAdESProperties(parameters, domSig, null, signatureValueEl); if (unsigned != null) { JAXBContext xadesJaxbContext = JAXBContext.newInstance(getXades13ObjectFactory().getClass()); Marshaller m = xadesJaxbContext.createMarshaller(); JAXBElement<UnsignedPropertiesType> el = getXades13ObjectFactory() .createUnsignedProperties(unsigned); m.marshal(el, getXAdESQualifyingProperties(parameters, doc)); } /* Output document */ ByteArrayOutputStream outputDoc = new ByteArrayOutputStream(); Result output = new StreamResult(outputDoc); Transformer xformer = TransformerFactory.newInstance().newTransformer(); Source source = new DOMSource(doc); xformer.transform(source, output); outputDoc.close(); return new InMemoryDocument(outputDoc.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } catch (JAXBException e) { throw new RuntimeException(e); } catch (XPathExpressionException e) { throw new RuntimeException(e); } catch (TransformerException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates signature part of assertion. Uses digest method algorithm * corresponding to the signature algorithm used. * * @param assertion//from ww w.j av a 2 s . c om * @param signatureAlgorithm * @return */ private Element createSignatureAndSignAssertion(Assertion assertion, SignatureAlgorithm signatureAlgorithm, SignInfo signInfo) { assert assertion != null; assert signatureAlgorithm != null; XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); Element assertionElement = marshallAssertion(assertion); List<Transform> transforms = createTransforms(); Reference ref = createReference(transforms, assertionElement.getAttribute(Assertion.ID_ATTRIB_NAME), // here we use the digest method which is corresponding to the // signature algorithm used signatureAlgorithm.getDigestMethod().toString()); SignedInfo signedInfo = createSignedInfo(Collections.singletonList(ref), signatureAlgorithm); DOMSignContext signingContext = new DOMSignContext(signInfo.getPrivateKey(), assertionElement); signingContext.putNamespacePrefix(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, "ec"); signingContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); // signature should be the second section in the assertion - after issuer // here we are sure that the structure of assertion is as follows: // 1) issuer 2) subject // we get subject node and enter signature before it and the result is: // 1) issuer 2) signature 3) subject Node subjectNode = assertionElement.getChildNodes().item(1); signingContext.setNextSibling(subjectNode); log.debug("Set SigningContext into assertion (after Issuer or as a first child in the assertion DOM)."); final KeyInfo keyInfo = createKeyInfo(signInfo); XMLSignature xmlSignature = factory.newXMLSignature(signedInfo, keyInfo); try { final long start = System.nanoTime(); xmlSignature.sign(signingContext); perfLog.trace("'signature.sign' took {} ms.", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); } catch (MarshalException e) { throw new IllegalStateException(e); } catch (XMLSignatureException e) { throw new IllegalStateException(e); } log.debug("Created Signature and sign it."); return assertionElement; }
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. c o 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); } }