@Override public void marshal(XmlWriter xwriter, String dsPrefix, XMLCryptoContext context) throws MarshalException { xwriter.writeStartElement(dsPrefix, "RetrievalMethod", XMLSignature.XMLNS); // TODO - see whether it is important to capture the "here" attribute as part of the // marshalling - do any of the tests fail? // add URI and Type attributes here = xwriter.writeAttribute("", "", "URI", uri); xwriter.writeAttribute("", "", "Type", type); // add Transforms elements if (!transforms.isEmpty()) { xwriter.writeStartElement(dsPrefix, "Transforms", XMLSignature.XMLNS); for (Transform transform : transforms) { ((DOMTransform)transform).marshal(xwriter, dsPrefix, context); } xwriter.writeEndElement(); // "Transforms" } xwriter.writeEndElement(); // "RetrievalMethod" }
@Override public Output get(Input input) throws Exception { Transform transform = input.getSignatureFactory().newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); Reference ref = input.getSignatureFactory().newReference("#propertiesObject", input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), Collections.singletonList(transform), null, null); String doc2 = "<ts:timestamp xmlns:ts=\"http:/timestamp\">" + System.currentTimeMillis() + "</ts:timestamp>"; InputStream is = new ByteArrayInputStream(doc2.getBytes("UTF-8")); Document doc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(is); DOMStructure structure = new DOMStructure(doc.getDocumentElement()); SignatureProperty prop = input.getSignatureFactory().newSignatureProperty(Collections.singletonList(structure), input.getSignatureId(), "property"); SignatureProperties properties = input.getSignatureFactory().newSignatureProperties(Collections.singletonList(prop), "properties"); XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(properties), "propertiesObject", null, null); XmlSignatureProperties.Output result = new Output(); result.setReferences(Collections.singletonList(ref)); result.setObjects(Collections.singletonList(propertiesObject)); return result; }
public XmlSignatureHandler() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { this.builderFactory = DocumentBuilderFactory.newInstance(); this.builderFactory.setNamespaceAware(true); this.transformerFactory = TransformerFactory.newInstance(); this.signatureFactory = XMLSignatureFactory.getInstance("DOM"); this.digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); this.transformList = new ArrayList<Transform>(2); this.transformList.add( signatureFactory.newTransform( Transform.ENVELOPED, (TransformParameterSpec) null)); this.transformList.add( signatureFactory.newTransform( "http://www.w3.org/TR/2001/REC-xml-c14n-20010315", (TransformParameterSpec) null)); this.canonicalizationMethod = this.signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); this.signatureMethod = this.signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); this.keyInfoFactory = this.signatureFactory.getKeyInfoFactory(); }
/** * Sign SAML element. * * @param element the element * @param privKey the priv key * @param pubKey the pub key * @return the element */ private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) { try { final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS); final XMLSignatureFactory sigFactory = XMLSignatureFactory .getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); final List<Transform> envelopedTransform = Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); // Create the SignatureMethod based on the type of key final SignatureMethod signatureMethod; final String algorithm = pubKey.getAlgorithm(); switch (algorithm) { case "DSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null); break; case "RSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); break; default: throw new RuntimeException("Error signing SAML element: Unsupported type of key"); } final CanonicalizationMethod canonicalizationMethod = sigFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); // Create the SignedInfo final SignedInfo signedInfo = sigFactory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections.singletonList(ref)); // Create a KeyValue containing the DSA or RSA PublicKey final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory(); final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValuePair)); // Convert the JDOM document to w3c (Java XML signature API requires w3c representation) final Element w3cElement = toDom(element); // Create a DOMSignContext and specify the DSA/RSA PrivateKey and // location of the resulting XMLSignature's parent element final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement); final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement); dsc.setNextSibling(xmlSigInsertionPoint); // Marshal, generate (and sign) the enveloped signature final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return toJdom(w3cElement); } catch (final Exception e) { throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e); } }
public RequestSigner ( final Configuration configuration ) throws Exception { this.fac = XMLSignatureFactory.getInstance ( "DOM" ); this.md = this.fac.newDigestMethod ( configuration.getDigestMethod (), null ); this.kif = this.fac.getKeyInfoFactory (); this.t = this.fac.newTransform ( Transform.ENVELOPED, (TransformParameterSpec)null ); this.ref = this.fac.newReference ( "", this.md, Collections.singletonList ( this.t ), null, null ); this.cm = this.fac.newCanonicalizationMethod ( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null ); }
public Document sign(FileInputStream fileStream, KeyPair keyPair) throws ParserConfigurationException, SAXException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(fileStream); DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement()); XMLSignatureFactory signFactory = XMLSignatureFactory .getInstance("DOM"); Reference ref = signFactory.newReference("", signFactory .newDigestMethod(digestMethod, null), Collections .singletonList(signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = signFactory.newSignedInfo(signFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), signFactory .newSignatureMethod(signatureMethod, null), Collections .singletonList(ref)); KeyInfoFactory kif = signFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keyPair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature signature = signFactory.newXMLSignature(si, ki); signature.sign(signContext); return document; }
public RetrievalMethod newRetrievalMethod(String uri, String type, List<? extends Transform> transforms) { if (uri == null) { throw new NullPointerException("uri must not be null"); } return new DOMRetrievalMethod(uri, type, transforms); }
public static void main(String[] args) throws NoSuchAlgorithmException { try { TransformService ts = TransformService.getInstance( Transform.BASE64, "DOM", "SomeProviderThatDoesNotExist"); } catch(NoSuchProviderException e) { // this is expected } }
/** * Creates a <code>DOMRetrievalMethod</code> containing the specified * URIReference and List of Transforms. * * @param uri the URI * @param type the type * @param transforms a list of {@link Transform}s. The list is defensively * copied to prevent subsequent modification. May be <code>null</code> * or empty. * @throws IllegalArgumentException if the format of <code>uri</code> is * invalid, as specified by Reference's URI attribute in the W3C * specification for XML-Signature Syntax and Processing * @throws NullPointerException if <code>uriReference</code> * is <code>null</code> * @throws ClassCastException if <code>transforms</code> contains any * entries that are not of type {@link Transform} */ public DOMRetrievalMethod(String uri, String type, List<? extends Transform> transforms) { if (uri == null) { throw new NullPointerException("uri cannot be null"); } if (transforms == null || transforms.isEmpty()) { this.transforms = Collections.emptyList(); } else { this.transforms = Collections.unmodifiableList( new ArrayList<Transform>(transforms)); for (int i = 0, size = this.transforms.size(); i < size; i++) { if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } } this.uri = uri; if (!uri.equals("")) { try { new URI(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException(e.getMessage()); } } this.type = type; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Transform)) { return false; } Transform otransform = (Transform)o; return getAlgorithm().equals(otransform.getAlgorithm()) && DOMUtils.paramsEqual(getParameterSpec(), otransform.getParameterSpec()); }
public String assinarDocumento(final String conteudoXml) throws Exception { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (InputStream certificadoStream = new ByteArrayInputStream(this.config.getCertificado())) { keyStore.load(certificadoStream, this.config.getCertificadoSenha().toCharArray()); } final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray())); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try (StringReader stringReader = new StringReader(conteudoXml)) { final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader)); for (final String elementoAssinavel : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } return this.converteDocumentParaXml(document); } }
/** * Returns a configuration for an XSL transformation. * * @param is * input stream of the XSL * @return XSL transform * @throws IllegalArgumentException * if <tt>is</tt> is <code>null</code> * @throws Exception * if an error during the reading of the XSL file occurs */ public static AlgorithmMethod getXslTranform(InputStream is) throws SAXException, IOException, ParserConfigurationException { if (is == null) { throw new IllegalArgumentException("is must not be null"); } Document doc = parseInput(is); DOMStructure stylesheet = new DOMStructure(doc.getDocumentElement()); XSLTTransformParameterSpec spec = new XSLTTransformParameterSpec(stylesheet); XmlSignatureTransform transformXslt = new XmlSignatureTransform(); transformXslt.setAlgorithm(Transform.XSLT); transformXslt.setParameterSpec(spec); return transformXslt; }
protected Reference createReference(XMLSignatureFactory fac, String uri, String type, SignatureType sigType, String id, Message message) throws InvalidAlgorithmParameterException, XmlSignatureException { try { List<Transform> transforms = getTransforms(fac, sigType, message); Reference ref = fac.newReference(uri, fac.newDigestMethod(getDigestAlgorithmUri(), null), transforms, type, id); return ref; } catch (NoSuchAlgorithmException e) { throw new XmlSignatureException("Wrong algorithm specified in the configuration.", e); } }
private boolean containsEnvelopedTransform(List<AlgorithmMethod> configuredTrafos) { for (AlgorithmMethod m : configuredTrafos) { if (Transform.ENVELOPED.equals(m.getAlgorithm())) { return true; } } return false; }
protected Reference createKeyInfoReference(XMLSignatureFactory fac, String keyInfoId, String digestAlgorithm) throws Exception { //NOPMD if (keyInfoId == null) { return null; } if (getConfiguration().getAddKeyInfoReference() == null) { return null; } if (!getConfiguration().getAddKeyInfoReference()) { return null; } LOG.debug("Creating reference to key info element with Id: {}", keyInfoId); List<Transform> transforms = new ArrayList<Transform>(1); Transform transform = fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); transforms.add(transform); return fac.newReference("#" + keyInfoId, fac.newDigestMethod(digestAlgorithm, null), transforms, null, null); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#"); // XPath v1 - slow... // Transform envelopedTransform = signatureFactory.newTransform( // CanonicalizationMethod.XPATH, new XPathFilterParameterSpec( // "not(ancestor-or-self::ds:Signature)", // xpathNamespaceMap)); // XPath v2 - fast... List<XPathType> types = new ArrayList<XPathType>(1); types.add(new XPathType("/descendant::*[name()='ds:Signature']", XPathType.Filter.SUBTRACT, xpathNamespaceMap)); Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.XPATH2, new XPathFilter2ParameterSpec(types)); transforms.add(envelopedTransform); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, this.dsReferenceId); references.add(reference); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null); transforms.add(envelopedTransform); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, null); references.add(reference); }
public Transform newTransform(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; try { spi = TransformService.getInstance(algorithm, "DOM"); } catch (NoSuchAlgorithmException nsae) { spi = TransformService.getInstance(algorithm, "DOM", getProvider()); } if (params == null) { spi.init(null); } else { spi.init(params, null); } return new DOMTransform(spi); }
private Element signSignature(String id, Element env, KeyInfoFactory keyInfoFactory, X509Credential credential) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { if (endorsingToken == null) return env; NodeList nl = env.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); if (e.hasAttributeNS(null, "Id")) { e.setAttributeNS(WSSecurityConstants.WSU_NS, "Id", e.getAttribute("Id")); e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } } env = SAMLUtil.loadElementFromString(XMLHelper.nodeToString(env)); DigestMethod digestMethod = xsf.newDigestMethod(DigestMethod.SHA1, null); List<Transform> transforms = new ArrayList<Transform>(2); transforms.add(xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",new ExcC14NParameterSpec(Collections.singletonList("xsd")))); List<Reference> refs = new ArrayList<Reference>(); Reference r = xsf.newReference("#"+id, digestMethod, transforms, null, null); refs.add(r); CanonicalizationMethod canonicalizationMethod = xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null); SignedInfo signedInfo = xsf.newSignedInfo(canonicalizationMethod, signatureMethod, refs); KeyInfo ki = generateKeyInfo(credential, keyInfoFactory, false); XMLSignature signature = xsf.newXMLSignature(signedInfo, ki); Node security = env.getElementsByTagNameNS(WSSecurityConstants.WSSE_NS, "Security").item(0); DOMSignContext signContext = new DOMSignContext(credential.getPrivateKey(), security); signContext.putNamespacePrefix(SAMLConstants.XMLSIG_NS, SAMLConstants.XMLSIG_PREFIX); signContext.putNamespacePrefix(SAMLConstants.XMLENC_NS, SAMLConstants.XMLENC_PREFIX); signature.sign(signContext); return env; }
public <T extends Node> T sign(T node) { checkNotNull(node); checkArgument(node instanceof Document || node instanceof Element); try { Element element = node instanceof Document ? ((Document) node).getDocumentElement() : (Element) node; DOMSignContext dsc = new DOMSignContext(privateKey, element); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); List<Transform> transformList = new LinkedList<>(); transformList.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transformList.add(signatureFactory.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); Node child = findFirstElementChild(element); ((Element) child).setIdAttribute("Id", true); String id = child.getAttributes().getNamedItem("Id").getNodeValue(); String uri = String.format("#%s", id); Reference reference = signatureFactory.newReference(uri, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null); SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory .newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); KeyInfoFactory kif = signatureFactory.getKeyInfoFactory(); X509Data x509Data = kif.newX509Data(Collections.singletonList(certificateChain[0])); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(x509Data)); XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(dsc); return node; } catch (Exception ex) { throw new IllegalArgumentException("Erro ao assinar XML.", ex); } }
private void sign(KeyStore keyStore, KeyPair keyPair, String alias, Document document, List<EbMSDataSource> dataSources) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, KeyException, MarshalException, XMLSignatureException, KeyStoreException { //XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(); DigestMethod sha1DigestMethod = signFactory.newDigestMethod(DigestMethod.SHA1,null); List<Transform> transforms = new ArrayList<Transform>(); transforms.add(signFactory.newTransform(Transform.ENVELOPED,(TransformParameterSpec)null)); Map<String,String> m = new HashMap<String,String>(); m.put("soap","http://schemas.xmlsoap.org/soap/envelope/"); transforms.add(signFactory.newTransform(Transform.XPATH,new XPathFilterParameterSpec("not(ancestor-or-self::node()[@soap:actor=\"urn:oasis:names:tc:ebxml-msg:service:nextMSH\"]|ancestor-or-self::node()[@soap:actor=\"http://schemas.xmlsoap.org/soap/actor/next\"])",m))); transforms.add(signFactory.newTransform(CanonicalizationMethod.INCLUSIVE,(TransformParameterSpec)null)); List<Reference> references = new ArrayList<Reference>(); references.add(signFactory.newReference("",sha1DigestMethod,transforms,null,null)); for (EbMSDataSource dataSource : dataSources) references.add(signFactory.newReference("cid:" + dataSource.getContentId(),sha1DigestMethod,Collections.emptyList(),null,null,DigestUtils.sha(IOUtils.toByteArray(dataSource.getInputStream())))); SignedInfo signedInfo = signFactory.newSignedInfo(signFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,(C14NMethodParameterSpec)null),signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1,null),references); List<XMLStructure> keyInfoElements = new ArrayList<XMLStructure>(); KeyInfoFactory keyInfoFactory = signFactory.getKeyInfoFactory(); keyInfoElements.add(keyInfoFactory.newKeyValue(keyPair.getPublic())); Certificate[] certificates = keyStore.getCertificateChain(alias); //keyInfoElements.add(keyInfoFactory.newX509Data(Arrays.asList(certificates))); keyInfoElements.add(keyInfoFactory.newX509Data(Collections.singletonList(certificates[0]))); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoElements); XMLSignature signature = signFactory.newXMLSignature(signedInfo,keyInfo); Element soapHeader = getFirstChildElement(document.getDocumentElement()); DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),soapHeader); signContext.putNamespacePrefix(XMLSignature.XMLNS,"ds"); signature.sign(signContext); }
private void signRequest(Element requestElement, PrivateKey privateKey, X509Certificate certificate) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild()); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory .getInstance("DOM"); String requestId = requestElement.getAttribute("RequestID"); requestElement.setIdAttribute("RequestID", true); List<Transform> transforms = new LinkedList<>(); transforms.add(xmlSignatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(xmlSignatureFactory.newTransform( CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null)); Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory .newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections .singletonList(keyInfoFactory.newX509Data(Collections .singletonList(certificate)))); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature( signedInfo, keyInfo); xmlSignature.sign(domSignContext); }
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException { // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html // byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes(); // load the document that's going to be signed DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(inputXml)); // create a key pair KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(512); KeyPair kp = kpg.generateKeyPair(); // sign the document DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(kp.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); OutputStream os = System.out; new XmlGenerator().generate(doc.getDocumentElement(), os); }
private static void sign(Document document, DigitalSignatureServiceSession session) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { Key key = new SecretKeySpec(session.getKey(), "HMACSHA1"); Node parentElement = document.getElementsByTagNameNS("urn:oasis:names:tc:dss:1.0:core:schema", "OptionalInputs") .item(0); DOMSignContext domSignContext = new DOMSignContext(key, parentElement); domSignContext.setDefaultNamespacePrefix("ds"); // XMLDSigRI Websphere work-around XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); List<Transform> transforms = new LinkedList<Transform>(); transforms.add(xmlSignatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add( xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null)); Reference reference = xmlSignatureFactory.newReference("", xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(SignatureMethod.HMAC_SHA1, null), Collections.singletonList(reference)); Element securityTokenReferenceElement = getSecurityTokenReference(session); KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); DOMStructure securityTokenReferenceDOMStructure = new DOMStructure(securityTokenReferenceElement); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(securityTokenReferenceDOMStructure)); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(domSignContext); }
@Nonnull @OverrideOnDemand @CodingStyleguideUnaware protected List <Transform> createTransformList (@Nonnull final XMLSignatureFactory aSignatureFactory) throws Exception { return CollectionHelper.makeUnmodifiable (aSignatureFactory.newTransform (Transform.ENVELOPED, (TransformParameterSpec) null)); }
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; } Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null); return ref; }
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) { String dm = DigestMethod.SHA1; //} Reference ref = fac.newReference("", fac.newDigestMethod(dm, null), transformers, null, null); return ref; }
/** * Sign the XML document using xmldsig. * @param document the document to sign; it will be modified by the method. * @param publicKey the public key from the key pair to sign the document. * @param privateKey the private key from the key pair to sign the document. * @return the signed document for chaining. */ public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory(); try { Reference ref =fac.newReference( "", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement()); KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey); KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue)); XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); } catch (Exception e) { Logger.warn("Error while signing an XML document.", e); } return document; }
/** * Signs the SAML assertion using the specified public and private keys. * * @param document * SAML assertion be signed. * @param privateKey * Private key used to sign SAML assertion. * @param publicKey * Public key used to sign SAML asserion. * @return w3c element representation of specified document. * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException * @throws KeyException * @throws MarshalException * @throws XMLSignatureException */ private Element signSamlAssertion(Document document, PrivateKey privateKey, X509Certificate certificate) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); List<Transform> envelopedTransform = Collections.singletonList(signatureFactory.newTransform( Transform.ENVELOPED, (TransformParameterSpec) null)); Reference ref = signatureFactory.newReference("", signatureFactory.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); SignatureMethod signatureMethod = null; if (certificate.getPublicKey() instanceof DSAPublicKey) { signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null); } else if (certificate.getPublicKey() instanceof RSAPublicKey) { signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(ref)); KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); X509Data data = keyInfoFactory.newX509Data(Collections.singletonList(certificate)); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(data)); Element w3cElement = document.getDocumentElement(); Node xmlSigInsertionPoint = getXmlSignatureInsertionLocation(w3cElement); DOMSignContext dsc = new DOMSignContext(privateKey, w3cElement, xmlSigInsertionPoint); XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return w3cElement; }
/** * Sign SAML element. * * @param element the element * @param privKey the priv key * @param pubKey the pub key * @return the element */ private org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) { try { final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS); final XMLSignatureFactory sigFactory = XMLSignatureFactory .getInstance("DOM", (Provider) Class.forName(providerName) .newInstance()); final List<Transform> envelopedTransform = Collections .singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); final Reference ref = sigFactory.newReference("", sigFactory .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); // Create the SignatureMethod based on the type of key final SignatureMethod signatureMethod; if (pubKey instanceof DSAPublicKey) { signatureMethod = sigFactory.newSignatureMethod( SignatureMethod.DSA_SHA1, null); } else if (pubKey instanceof RSAPublicKey) { signatureMethod = sigFactory.newSignatureMethod( SignatureMethod.RSA_SHA1, null); } else { throw new RuntimeException("Error signing SAML element: Unsupported type of key"); } final CanonicalizationMethod canonicalizationMethod = sigFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); // Create the SignedInfo final SignedInfo signedInfo = sigFactory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections .singletonList(ref)); // Create a KeyValue containing the DSA or RSA PublicKey final KeyInfoFactory keyInfoFactory = sigFactory .getKeyInfoFactory(); final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections .singletonList(keyValuePair)); // Convert the JDOM document to w3c (Java XML signature API requires // w3c representation) final org.w3c.dom.Element w3cElement = toDom(element); // Create a DOMSignContext and specify the DSA/RSA PrivateKey and // location of the resulting XMLSignature's parent element final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement); final org.w3c.dom.Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement); dsc.setNextSibling(xmlSigInsertionPoint); // Marshal, generate (and sign) the enveloped signature final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return toJdom(w3cElement); } catch (final Exception e) { throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e); } }
private static Element signSamlElement(final Element element, final PrivateKey privKey, final PublicKey pubKey) { try { final String providerName = System.getProperty("jsr105Provider", JSR_105_PROVIDER); final XMLSignatureFactory sigFactory = XMLSignatureFactory .getInstance("DOM", (Provider) Class.forName(providerName) .newInstance()); final List envelopedTransform = Collections .singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); final Reference ref = sigFactory.newReference("", sigFactory .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); // Create the SignatureMethod based on the type of key SignatureMethod signatureMethod; if (pubKey instanceof DSAPublicKey) { signatureMethod = sigFactory.newSignatureMethod( SignatureMethod.DSA_SHA1, null); } else if (pubKey instanceof RSAPublicKey) { signatureMethod = sigFactory.newSignatureMethod( SignatureMethod.RSA_SHA1, null); } else { throw new RuntimeException( "Error signing SAML element: Unsupported type of key"); } final CanonicalizationMethod canonicalizationMethod = sigFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); // Create the SignedInfo final SignedInfo signedInfo = sigFactory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections .singletonList(ref)); // Create a KeyValue containing the DSA or RSA PublicKey final KeyInfoFactory keyInfoFactory = sigFactory .getKeyInfoFactory(); final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections .singletonList(keyValuePair)); // Convert the JDOM document to w3c (Java XML signature API requires // w3c // representation) org.w3c.dom.Element w3cElement = toDom(element); // Create a DOMSignContext and specify the DSA/RSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privKey, w3cElement); org.w3c.dom.Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement); dsc.setNextSibling(xmlSigInsertionPoint); // Marshal, generate (and sign) the enveloped signature XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return toJdom(w3cElement); } catch (final Exception e) { throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e); } }
/** * Creates a <code>DOMRetrievalMethod</code> from an element. * * @param rmElem a RetrievalMethod element */ public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context, Provider provider) throws MarshalException { // get URI and Type attributes uri = DOMUtils.getAttributeValue(rmElem, "URI"); type = DOMUtils.getAttributeValue(rmElem, "Type"); // get here node here = rmElem.getAttributeNodeNS(null, "URI"); boolean secVal = Utils.secureValidation(context); // get Transforms, if specified List<Transform> newTransforms = new ArrayList<Transform>(); Element transformsElem = DOMUtils.getFirstChildElement(rmElem); if (transformsElem != null) { String localName = transformsElem.getLocalName(); String namespace = transformsElem.getNamespaceURI(); if (!localName.equals("Transforms") || !XMLSignature.XMLNS.equals(namespace)) { throw new MarshalException("Invalid element name: " + namespace + ":" + localName + ", expected Transforms"); } Element transformElem = DOMUtils.getFirstChildElement(transformsElem, "Transform", XMLSignature.XMLNS); while (transformElem != null) { String name = transformElem.getLocalName(); namespace = transformElem.getNamespaceURI(); if (!name.equals("Transform") || !XMLSignature.XMLNS.equals(namespace)) { throw new MarshalException("Invalid element name: " + name + ", expected Transform"); } newTransforms.add (new DOMTransform(transformElem, context, provider)); if (secVal && newTransforms.size() > DOMReference.MAXIMUM_TRANSFORM_COUNT) { String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " " + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } transformElem = DOMUtils.getNextSiblingElement(transformElem); } } if (newTransforms.isEmpty()) { this.transforms = Collections.emptyList(); } else { this.transforms = Collections.unmodifiableList(newTransforms); } }
@Override public List<Transform> getTransforms() { return transforms; }
@Override public Data dereference(XMLCryptoContext context) throws URIReferenceException { if (context == null) { throw new NullPointerException("context cannot be null"); } /* * If URIDereferencer is specified in context; use it, otherwise use * built-in. */ URIDereferencer deref = context.getURIDereferencer(); if (deref == null) { deref = DOMURIDereferencer.INSTANCE; } Data data = deref.dereference(this, context); // pass dereferenced data through Transforms try { for (Transform transform : transforms) { data = transform.transform(data, context); } } catch (Exception e) { throw new URIReferenceException(e); } // guard against RetrievalMethod loops if (data instanceof NodeSetData && Utils.secureValidation(context)) { NodeSetData nsd = (NodeSetData)data; Iterator<?> i = nsd.iterator(); if (i.hasNext()) { Node root = (Node)i.next(); if ("RetrievalMethod".equals(root.getLocalName())) { throw new URIReferenceException( "It is forbidden to have one RetrievalMethod point " + "to another when secure validation is enabled"); } } } return data; }
public List<Transform> getTransforms() { return Collections.emptyList(); }
public void dsig() throws Exception { Provider p = Security.getProvider("ApacheXMLDSig"); TransformService.getInstance(Transform.XPATH, "DOM", p); }
@Override public Output get(Input input) throws Exception { //NOPMD XmlSignatureProperties.Output result = new Output(); if (!isAddSignedSignatureProperties() && !isAddSignedDataObjectPropeties()) { LOG.debug("XAdES signature properties are empty. Therefore no XAdES element will be added to the signature."); return result; } String signedPropertiesId = "_" + UUID.randomUUID().toString(); List<Transform> transforms = Collections.emptyList(); Reference ref = input.getSignatureFactory().newReference("#" + signedPropertiesId, input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), transforms, "http://uri.etsi.org/01903#SignedProperties", null); Node parent = input.getParent(); Document doc; if (Node.DOCUMENT_NODE == parent.getNodeType()) { doc = (Document) parent; // enveloping } else { doc = parent.getOwnerDocument(); // enveloped } Element qualifyingProperties = createElement("QualifyingProperties", doc, input); setIdAttributeFromHeader(XmlSignatureConstants.HEADER_XADES_QUALIFYING_PROPERTIES_ID, qualifyingProperties, input); String signatureId = input.getSignatureId(); if (signatureId == null || signatureId.isEmpty()) { LOG.debug("No signature Id configured. Therefore a value is generated."); // generate one signatureId = "_" + UUID.randomUUID().toString(); // and set to output result.setSignatureId(signatureId); } setAttribute(qualifyingProperties, "Target", "#" + signatureId); Element signedProperties = createElement("SignedProperties", doc, input); qualifyingProperties.appendChild(signedProperties); setAttribute(signedProperties, "Id", signedPropertiesId); signedProperties.setIdAttribute("Id", true); addSignedSignatureProperties(doc, signedProperties, input); String contentReferenceId = addSignedDataObjectProperties(doc, signedProperties, input); result.setContentReferenceId(contentReferenceId); DOMStructure structure = new DOMStructure(qualifyingProperties); XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(structure), null, null, null); result.setReferences(Collections.singletonList(ref)); result.setObjects(Collections.singletonList(propertiesObject)); return result; }