code: private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
          try {
              val providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
  
              val clazz = Class.forName(providerName);
              val sigFactory = XMLSignatureFactory
                  .getInstance("DOM", (Provider) clazz.getDeclaredConstructor().newInstance());
  
              val envelopedTransform = CollectionUtils.wrap(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
  
              val ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory
                  .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
  
              val signatureMethod = getSignatureMethodFromPublicKey(pubKey, sigFactory);
              val canonicalizationMethod = sigFactory
                  .newCanonicalizationMethod(
                      CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                      (C14NMethodParameterSpec) null);
  
              val signedInfo = sigFactory.newSignedInfo(canonicalizationMethod, signatureMethod, CollectionUtils.wrap(ref));
  
              val keyInfoFactory = sigFactory.getKeyInfoFactory();
              val keyValuePair = keyInfoFactory.newKeyValue(pubKey);
  
              val keyInfo = keyInfoFactory.newKeyInfo(CollectionUtils.wrap(keyValuePair));
              val w3cElement = toDom(element);
  
              val dsc = new DOMSignContext(privKey, w3cElement);
  
              val xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
              dsc.setNextSibling(xmlSigInsertionPoint);
  
              val signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
              signature.sign(dsc);
  
              return toJdom(w3cElement);
  
          } catch (final Exception e) {
              throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
          }
      }
docs: Sign SAML element.
  
  @param element the element
  @param privKey the priv key
  @param pubKey  the pub key
  @return the element