List of usage examples for javax.xml.crypto.dsig SignatureMethod RSA_SHA1
String RSA_SHA1
To view the source code for javax.xml.crypto.dsig SignatureMethod RSA_SHA1.
Click Source Link
From source file:be.fedict.eid.tsl.TrustServiceList.java
private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {//ww w . j a va 2 s. c o m XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); LOG.debug("xml signature factory: " + signatureFactory.getClass().getName()); LOG.debug("loader: " + signatureFactory.getClass().getClassLoader()); XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement()); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Reference> references = new LinkedList<Reference>(); List<Transform> transforms = new LinkedList<Transform>(); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + tslId, digestMethod, transforms, null, null); references.add(reference); String signatureId = "xmldsig-" + UUID.randomUUID().toString(); List<XMLObject> objects = new LinkedList<XMLObject>(); addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects); SignatureMethod signatureMethod; if (isJava6u18OrAbove()) { signatureMethod = signatureFactory .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); } else { signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); List<Object> keyInfoContent = new LinkedList<Object>(); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); x509DataObjects.add(certificate); x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(), certificate.getSerialNumber())); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); KeyValue keyValue; try { keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey()); } catch (KeyException e) { throw new RuntimeException("key exception: " + e.getMessage(), e); } keyInfoContent.add(keyValue); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); String signatureValueId = signatureId + "-signature-value"; XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId, signatureValueId); xmlSignature.sign(signContext); }
From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java
/** * Sign DOM document//from w ww . j a v a2s . c om * * @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 w w .j a va2 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.apache.jcp.xml.dsig.internal.dom.DOMSignatureMethod.java
static SignatureMethod unmarshal(Element smElem) throws MarshalException { String alg = DOMUtils.getAttributeValue(smElem, "Algorithm"); if (alg.equals(SignatureMethod.RSA_SHA1)) { return new SHA1withRSA(smElem); } else if (alg.equals(RSA_SHA256)) { return new SHA256withRSA(smElem); } else if (alg.equals(RSA_SHA384)) { return new SHA384withRSA(smElem); } else if (alg.equals(RSA_SHA512)) { return new SHA512withRSA(smElem); } else if (alg.equals(SignatureMethod.DSA_SHA1)) { return new SHA1withDSA(smElem); } else if (alg.equals(ECDSA_SHA1)) { return new SHA1withECDSA(smElem); } else if (alg.equals(ECDSA_SHA256)) { return new SHA256withECDSA(smElem); } else if (alg.equals(ECDSA_SHA384)) { return new SHA384withECDSA(smElem); } else if (alg.equals(ECDSA_SHA512)) { return new SHA512withECDSA(smElem); } else if (alg.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(smElem); } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(smElem); } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(smElem); } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(smElem); } else if (alg.equals(GOSTR34102001_GOSTR3411)) { return new GOST3411withGOST3410(smElem); } else if (alg.equals(GOSTR34102001_GOSTR3411URN)) { return new GOST3411withGOST3410URN(smElem); } else {//from w w w. java2 s . co m throw new MarshalException("unsupported SignatureMethod algorithm: " + alg); } }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception { Reference ref = initReference(fac); String cm = null;/* w ww . j a v a 2s. c o m*/ cm = map.getProperty(CANONICALIZATIONMETHOD); String sigmethod = null; sigmethod = map.getProperty(SIGNATURE_METHOD); if (sigmethod == null) { sigmethod = SignatureMethod.RSA_SHA1; } if (cm == null) { cm = CanonicalizationMethod.EXCLUSIVE; } SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(cm, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigmethod, null), Collections.singletonList(ref)); return si; }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
public String getSignedMessage(SignatureHelper signatureHelper) { if (_responseDocument == null) { try {// w ww . j a va 2 s. c o m _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true); } catch (OAException | XMLStreamException e) { _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e); return null; } } signatureHelper.tagIdAttributes(_responseDocument); KeyPair keypair = signatureHelper.getKeyPairFromKeystore(); // Set signing context with PrivateKey and root of the Document DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), _responseDocument.getDocumentElement()); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; SignedInfo si = null; XMLSignature signature = null; try { // Create reference for "" -> root of the document // SAML requires enveloped transform List<Transform> transformsList = new ArrayList<>(); transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null)); ref = fac.newReference("#" + getId(), fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) // .. some selection here; nothing fancy, just trying to switch based on signing key format String sigMethod; String keyAlg = keypair.getPrivate().getAlgorithm(); if (keyAlg.contains("RSA")) { sigMethod = SignatureMethod.RSA_SHA1; } else if (keyAlg.contains("DSA")) { sigMethod = SignatureMethod.DSA_SHA1; } else { _logger.error("Unknown signing key algorithm: {}", keyAlg); return null; } si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigMethod, null), Collections.singletonList(ref)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); signature = fac.newXMLSignature(si, ki); // Sign! signature.sign(dsc); String s = XMLUtils.getStringFromDocument(_responseDocument); _logger.info("Document after signing whole message:\n{}", s); return s; } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { _logger.error("Could not create reference to signable content: {}", e.getMessage(), e); return null; } catch (KeyException e) { _logger.error("Could not establish key info: {}", e.getMessage(), e); return null; } catch (MarshalException | XMLSignatureException e) { _logger.error("Error signing document: {}", e.getMessage(), e); return null; } catch (OAException e) { _logger.error("Error creating string from XML document: {}", e.getMessage(), e); return null; } }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
/** * Requires the responseDocument to be already initialized, just adding another * Signature section to the existing documnet * @param signatureHelper/*from w w w .j a v a2 s . 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
public String signQueryString(String queryString) throws SamlR2SignatureException { try {//from ww w . ja v a 2s . co m if (queryString == null || queryString.length() == 0) { logger.error("SAML 2.0 Qery string null"); throw new SamlR2SignatureException("SAML 2.0 Qery string null"); } if (logger.isDebugEnabled()) logger.debug("Received SAML 2.0 Query string [" + queryString + "] for signing"); PrivateKey privateKey = (PrivateKey) this.getKeyResolver().getPrivateKey(); String keyAlgorithm = privateKey.getAlgorithm(); Signature signature = null; String algURI = null; if (keyAlgorithm.equals("RSA")) { signature = Signature.getInstance(SHA1_WITH_RSA); algURI = SignatureMethod.RSA_SHA1; } else if (keyAlgorithm.equals("DSA")) { signature = Signature.getInstance(SHA1_WITH_DSA); algURI = SignatureMethod.DSA_SHA1; } else { throw new SamlR2SignatureException( "SAML 2.0 Signature does not support provided key's algorithm " + keyAlgorithm); } if (queryString.charAt(queryString.length() - 1) != '&') { queryString = queryString + "&"; } queryString += "SigAlg=" + URLEncoder.encode(algURI, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signing SAML 2.0 Query string [" + queryString + "]"); signature.initSign(privateKey); signature.update(queryString.getBytes()); byte[] sigBytes = null; sigBytes = signature.sign(); if (sigBytes == null || sigBytes.length == 0) { logger.error("Cannot generate signed query string, Signature created 'null' value."); throw new SamlR2SignatureException( "Cannot generate signed query string, Signature created 'null' value."); } Base64 encoder = new Base64(); String encodedSig = new String(encoder.encode(sigBytes), "UTF-8"); queryString += "&Signature=" + URLEncoder.encode(encodedSig, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signed SAML 2.0 Query string [" + queryString + "]"); return queryString; } catch (Exception e) { throw new SamlR2SignatureException("Error generating SAML 2.0 Query string signature " + e.getMessage(), e); } }
From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
public void validateQueryString(RoleDescriptorType md, String queryString) throws SamlR2SignatureException, SamlR2SignatureValidationException { try {/*from w w w.j a v a2 s . c o m*/ X509Certificate cert = getX509Certificate(md); if (cert == null) { logger.error("No Certificate found in Metadata " + md.getID()); throw new SamlR2SignatureException("No Certificate found in Metadata " + md.getID()); } if (queryString == null || queryString.length() == 0) { logger.error("SAML 2.0 Qery string null"); throw new SamlR2SignatureException("SAML 2.0 Qery string null"); } if (logger.isTraceEnabled()) logger.trace("SAML 2.0 Query string to validate [" + queryString + "]"); StringTokenizer st = new StringTokenizer(queryString, "&"); String samlParam; String samlRequest = null; String samlResponse = null; String relayState = null; String sigAlg = null; String encSig = null; while (st.hasMoreTokens()) { samlParam = st.nextToken(); if (samlParam.startsWith("SAMLRequest")) { samlRequest = samlParam; } else if (samlParam.startsWith("SAMLResponse")) { samlResponse = samlParam; } else if (samlParam.startsWith("RelayState")) { relayState = samlParam; } else if (samlParam.startsWith("SigAlg")) { sigAlg = samlParam; } else if (samlParam.startsWith("Signature")) { encSig = samlParam; } else { // Ignore this token ... logger.warn("Non-SAML 2.0 parameter ignored " + samlParam); } } if ((samlRequest == null || samlRequest.equals("")) && (samlResponse == null || samlResponse.equals(""))) throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain either 'SAMLRequest' or 'SAMLResponse' parameter"); if (sigAlg == null || sigAlg.equals("")) throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'SigAlg' parameter"); if (encSig == null || encSig.equals("")) { throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'Signature' parameter"); } // Re-order paramters just in case they were mixed-up while getting here. String newQueryString = null; if (samlRequest != null) { newQueryString = samlRequest; } else { newQueryString = samlResponse; } if (relayState != null) { newQueryString += "&" + relayState; } newQueryString += "&" + sigAlg; if (logger.isDebugEnabled()) logger.debug( "SAML 2.0 Query string signature validation for (re-arranged) [" + newQueryString + "]"); int sigAlgValueIndex = sigAlg.indexOf('='); // Get Signature Algorithm String sigAlgValue = sigAlg.substring(sigAlgValueIndex + 1); if (sigAlgValue == null || sigAlgValue.equals("")) { throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'SigAlg' parameter value"); } sigAlgValue = URLDecoder.decode(sigAlgValue, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("SigAlg=" + sigAlgValue); // Get Signature value int encSigValueIndex = encSig.indexOf('='); String signatureEnc = encSig.substring(encSigValueIndex + 1); if (signatureEnc == null || signatureEnc.equals("")) { throw new SamlR2SignatureValidationException( "SAML 2.0 Query string MUST contain a 'Signature' parameter value"); } signatureEnc = URLDecoder.decode(signatureEnc, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signature=" + signatureEnc); // base-64 decode the signature value byte[] signatureBin = null; Base64 decoder = new Base64(); signatureBin = decoder.decode(signatureEnc.getBytes()); // get Signature instance based on algorithm // TODO : Support SHA-256 Signature signature = null; if (sigAlgValue.equals(SignatureMethod.DSA_SHA1)) { signature = Signature.getInstance(SHA1_WITH_DSA); } else if (sigAlgValue.equals(SignatureMethod.RSA_SHA1)) { signature = Signature.getInstance(SHA1_WITH_RSA); } else { throw new SamlR2SignatureException("SAML 2.0 Siganture does not support algorithm " + sigAlgValue); } // now verify signature signature.initVerify(cert); signature.update(newQueryString.getBytes()); if (!signature.verify(signatureBin)) { // TODO : Get information about the error ?! throw new SamlR2SignatureValidationException("Invalid digital signature"); } if (!validateCertificate(md, null)) { throw new SamlR2SignatureValidationException("Certificate is not valid, check logs for details"); } } catch (Exception e) { logger.error("Cannot verify digital SAML 2.0 Query string signature " + e.getMessage(), e); throw new SamlR2SignatureException( "Cannot verify digital SAML 2.0 Query string signature " + e.getMessage(), e); } }
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/*w ww . ja v a 2s . c o m*/ * @param id * @return */ protected Document sign(Document doc, String id) throws SamlR2SignatureException { try { Certificate cert = keyResolver.getCertificate(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider); if (logger.isDebugEnabled()) logger.debug("Creating XML DOM Digital Siganture (not signing yet!)"); // Create a Reference to the enveloped document and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. // The URI must be the assertion ID List<Transform> transforms = new ArrayList<Transform>(); transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // Magically, this solves assertion DS validation when embedded in a signed response :) transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); // Use signature method based on key algorithm. String signatureMethod = SignatureMethod.DSA_SHA1; if (keyResolver.getPrivateKey().getAlgorithm().equals("RSA")) signatureMethod = SignatureMethod.RSA_SHA1; logger.debug("Using signature method " + signatureMethod); // Create the SignedInfo, with the X509 Certificate /* SignedInfo si = fac.newSignedInfo (fac.newCanonicalizationMethod (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); */ SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); // Create a KeyInfo and add the Certificate to it KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); //KeyValue kv = kif.newKeyValue(keyResolver.getCertificate().getPublicKey()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); if (logger.isDebugEnabled()) logger.debug("Signing SAMLR2 Identity Artifact ..."); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(keyResolver.getPrivateKey(), doc.getDocumentElement(), doc.getDocumentElement().getFirstChild()); // Sign the assertion signature.sign(dsc); if (logger.isDebugEnabled()) logger.debug("Signing SAMLR2 Identity Artifact ... DONE!"); return doc; } catch (NoSuchAlgorithmException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (XMLSignatureException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (MarshalException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (SSOKeyResolverException e) { throw new SamlR2SignatureException(e.getMessage(), e); } }