List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory getInstance
public static XMLSignatureFactory getInstance(String mechanismType)
XMLSignatureFactory
that supports the specified XML processing mechanism and representation type (ex: "DOM"). From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
@Override public List<AdvancedSignature> getCounterSignatures() { // see ETSI TS 101 903 V1.4.2 (2010-12) pp. 38/39/40 try {/*from w w w .j av a 2 s . com*/ NodeList counterSigs = XMLUtils.getNodeList(signatureElement, "./ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties" + "/xades:CounterSignature"); if (counterSigs == null) { return null; } List<AdvancedSignature> xadesList = new ArrayList<AdvancedSignature>(); for (int i = 0; i < counterSigs.getLength(); i++) { Element counterSigEl = (Element) counterSigs.item(i); Element signatureEl = XMLUtils.getElement(counterSigEl, "./ds:Signature"); // Verify that the element is a proper signature by trying to build a XAdESSignature out of it XAdESSignature xCounterSig = new XAdESSignature(signatureEl); // Verify that there is a ds:Reference element with a Type set to: http://uri.etsi.org/01903#CountersignedSignature // (as per the XAdES spec) XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = factory.unmarshalXMLSignature(new DOMStructure(signatureEl)); LOG.info("Verifying countersignature References"); for (Object refobj : signature.getSignedInfo().getReferences()) { Reference ref = (Reference) refobj; if (ref.getType() != null && ref.getType().equals("http://uri.etsi.org/01903#CountersignedSignature")) { // Ok, this seems to be a countersignature // Verify that the digest is that of the signature value if (ref.validate(new DOMValidateContext(xCounterSig.getSigningCertificate().getPublicKey(), XMLUtils.getElement(signatureElement, "./ds:SignatureValue")))) { LOG.info("Reference verification succeeded, adding countersignature"); xadesList.add(xCounterSig); } else { LOG.warning( "Skipping countersignature because the Reference doesn't contain a hash of the embedding SignatureValue"); } break; } } } return xadesList; } catch (XPathExpressionException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING); } catch (MarshalException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING); } catch (XMLSignatureException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING); } }
From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java
/** * X509??./* w ww . ja v a 2 s . c o m*/ * @param privateKeyFileName ??? * @param certificateFileName ?? * @param rootCertificateFileNames ?? * @throws IOException IOException * @throws NoSuchAlgorithmException NoSuchAlgorithmException * @throws InvalidKeySpecException InvalidKeySpecException * @throws CertificateException CertificateException */ public static void configureX509(String privateKeyFileName, String certificateFileName, String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); // Read RootCA Certificate x509RootCertificateFileNames = new ArrayList<String>(); if (rootCertificateFileNames != null) { for (String fileName : rootCertificateFileNames) { x509RootCertificateFileNames.add(fileName); } } // Read Private Key InputStream is = null; if (privateKeyFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH); } else { is = new FileInputStream(privateKeyFileName); } PEMReader privateKeyPemReader = new PEMReader(is); byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes(); PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec()); // Read Certificate if (certificateFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH); } else { is = new FileInputStream(certificateFileName); } PEMReader serverCertificatePemReader; serverCertificatePemReader = new PEMReader(is); byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes(); CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE); x509Certificate = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert)); // Create the KeyInfo containing the X509Data KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); List x509Content = new ArrayList(); x509Content.add(x509Certificate.getSubjectX500Principal().getName()); x509Content.add(x509Certificate); X509Data xd = keyInfoFactory.newX509Data(x509Content); keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd)); // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/ }
From source file:io.personium.common.auth.token.TransCellAccessToken.java
/** * X509??.//from w w w . ja va2 s .c o m * @param privateKeyFileName ??? * @param certificateFileName ?? * @param rootCertificateFileNames ?? * @throws IOException IOException * @throws NoSuchAlgorithmException NoSuchAlgorithmException * @throws InvalidKeySpecException InvalidKeySpecException * @throws CertificateException CertificateException * @throws InvalidNameException InvalidNameException */ public static void configureX509(String privateKeyFileName, String certificateFileName, String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, InvalidNameException { xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); // Read RootCA Certificate x509RootCertificateFileNames = new ArrayList<String>(); if (rootCertificateFileNames != null) { for (String fileName : rootCertificateFileNames) { x509RootCertificateFileNames.add(fileName); } } // Read Private Key InputStream is = null; if (privateKeyFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH); } else { is = new FileInputStream(privateKeyFileName); } PEMReader privateKeyPemReader = new PEMReader(is); byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes(); PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec()); // Read Certificate if (certificateFileName == null) { is = TransCellAccessToken.class.getClassLoader() .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH); } else { is = new FileInputStream(certificateFileName); } PEMReader serverCertificatePemReader; serverCertificatePemReader = new PEMReader(is); byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes(); CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE); x509Certificate = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert)); // Create the KeyInfo containing the X509Data KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); List x509Content = new ArrayList(); x509Content.add(x509Certificate.getSubjectX500Principal().getName()); x509Content.add(x509Certificate); X509Data xd = keyInfoFactory.newX509Data(x509Content); keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd)); // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils String dn = x509Certificate.getSubjectX500Principal().getName(); LdapName ln = new LdapName(dn); for (Rdn rdn : ln.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { PersoniumCoreUtils.setFQDN(rdn.getValue().toString()); break; } } // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/ }
From source file:be.fedict.eid.tsl.TrustServiceList.java
public X509Certificate verifySignature() { if (null == this.tslDocument) { LOG.debug("first save the document"); return null; }/*from ww w . j a v a 2s .co m*/ Node signatureNode = getSignatureNode(); if (null == signatureNode) { LOG.debug("no ds:Signature element present"); return null; } KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector(); DOMValidateContext valContext = new DOMValidateContext(keyInfoKeySelector, signatureNode); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new RuntimeException("XML signature parse error: " + e.getMessage(), e); } boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { throw new RuntimeException("XML signature error: " + e.getMessage(), e); } // TODO: check what has been signed if (coreValidity) { LOG.debug("signature valid"); return keyInfoKeySelector.getCertificate(); } LOG.debug("signature invalid"); return null; }
From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java
@Override public List<AdvancedSignature> getCounterSignatures() { // see ETSI TS 101 903 V1.4.2 (2010-12) pp. 38/39/40 try {//from w w w . j a v a2s. co m NodeList counterSigs = DSSXMLUtils.getNodeList(signatureElement, XPATH_COUNTER_SIGNATURE); if (counterSigs == null) { return null; } List<AdvancedSignature> xadesList = new ArrayList<AdvancedSignature>(); for (int i = 0; i < counterSigs.getLength(); i++) { Element counterSigEl = (Element) counterSigs.item(i); Element signatureEl = DSSXMLUtils.getElement(counterSigEl, XPATH_SIGNATURE); // Verify that the element is a proper signature by trying to build a XAdESSignature out of it XAdESSignature xCounterSig = new XAdESSignature(signatureEl, certPool); /* * Verify that there is a ds:Reference element with a Type set to: * http://uri.etsi.org/01903#CountersignedSignature (as per the XAdES spec) */ XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); javax.xml.crypto.dsig.XMLSignature signature = factory .unmarshalXMLSignature(new DOMStructure(signatureEl)); LOG.info("Verifying countersignature References"); for (Object refobj : signature.getSignedInfo().getReferences()) { Reference ref = (Reference) refobj; if (ref.getType() != null && ref.getType().equals(XADES_COUNTERSIGNED_SIGNATURE)) { // Ok, this seems to be a CounterSignature // Verify that the digest is that of the signature value CertificateToken certToken = xCounterSig.getSigningCertificate().getCertToken(); PublicKey publicKey = certToken.getCertificate().getPublicKey(); if (ref.validate(new DOMValidateContext(publicKey, DSSXMLUtils.getElement(signatureElement, XPATH_SIGNATURE_VALUE)))) { LOG.info("Reference verification succeeded, adding countersignature"); xadesList.add(xCounterSig); } else { LOG.warning( "Skipping countersignature because the Reference doesn't contain a hash of the embedding SignatureValue"); } break; } } } return xadesList; } catch (MarshalException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING, e); } catch (XMLSignatureException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING, e); } }
From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java
/** * Sign DOM document/*from w ww . j av a 2 s . c o m*/ * * @param documentElement * document to be signed * @param nextSibling * next sibling in document, dsig is added before this one * @param identity * Identity to sign with * @throws NoSuchAlgorithmException * signing algorithm not found * @throws InvalidAlgorithmParameterException * invalid signing algo param * @throws MarshalException * error marshalling signature * @throws XMLSignatureException * error during signing */ public static void signDocument(Element documentElement, Node nextSibling, KeyStore.PrivateKeyEntry identity) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { // get document ID String documentId = documentElement.getAttribute("ID"); LOG.debug("document ID=" + documentId); // fix for recent versions of Apache xmlsec. documentElement.setIdAttribute("ID", true); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignContext signContext = new DOMSignContext(identity.getPrivateKey(), documentElement, nextSibling); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); javax.xml.crypto.dsig.DigestMethod digestMethod = signatureFactory .newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null); List<javax.xml.crypto.dsig.Transform> transforms = new LinkedList<javax.xml.crypto.dsig.Transform>(); transforms.add(signatureFactory.newTransform(javax.xml.crypto.dsig.Transform.ENVELOPED, (TransformParameterSpec) null)); javax.xml.crypto.dsig.Transform exclusiveTransform = signatureFactory .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + documentId, digestMethod, transforms, null, null); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); List<Object> keyInfoContent = new LinkedList<Object>(); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); for (X509Certificate certificate : Saml2Util.getCertificateChain(identity)) { x509DataObjects.add(certificate); } javax.xml.crypto.dsig.keyinfo.X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(signContext); }
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 {// w ww. ja v a 2 s. co 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.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias, String keyPassword) {//from w w w . j a v a2 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. j a v a 2 s . c om _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/*www. j a v a2 s.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; } }