3

I have to implement a similar logic to this in Java.

I have an XML which is not signed and the message before sending to Service provider. I have both private and public key and unsigned XML.

Can some one help me providing a code snippet exactly which method to called in order to sign the message using public and private key.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Ashish
  • 39
  • 1
  • 2

3 Answers3

2

You create a Signature object and set the signing properties on it

signature.setSigningCredential(credential);
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

Then you set the signature object on the Response

.setSignature(signature)

Next you marshall the response object

XMLObjectProviderRegistrySupport
   .getMarshallerFactory()
   .getMarshaller(response)
   .marshall(response);

Lastly you use the Signer class to perform the signing

Signer.signObject(signature);

I have more information in this post on my blog

Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82
Stefan Rasmusson
  • 5,445
  • 3
  • 21
  • 48
  • You deserve more upvotes on this answer. Thanks a lot for the clarification and for the blog post as well. Great article, I found it useful. – Gozus19 Sep 10 '20 at 15:52
2

You can also use onelogin saml-java utils from Onelogin Saml Java - that one seems to be much easier to use (they have method to load public, private key, document from string, etc. Then you can use it to sign either the whole SAML response or to sign assertion and then the response:

Document document = Util.loadXML(saml); //loads string to document

//load private key and certificate
X509Certificate cert = Util.loadCert(pubKeyBytes);
PrivateKey privateKey = Util.loadPrivateKey(privKeyBytes);

//sign the response
String signedResponse = Util.addSign(document, privateKey, cert, null);

to use this library, just add

<dependency>
    <groupId>com.onelogin</groupId>
    <artifactId>java-saml</artifactId>
    <version>2.0.0</version>
</dependency>

dependency to your project's pom.xml

shimon001
  • 733
  • 9
  • 24
-1

For opensaml3, use:

import org.opensaml.xmlsec.signature.support.Signer;
double-beep
  • 5,031
  • 17
  • 33
  • 41
hzhsun
  • 114
  • 1
  • 5
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – double-beep Apr 18 '19 at 15:06