private static org.jdom2.Element signSamlElement(final org.jdom2.Element element, final PrivateKey privKey, final PublicKey pubKey) {
        try {
            LOGGER.trace("Attempting to sign Element: [{}]", element);
            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 new DOMBuilder().build(w3cElement);
        } catch (final Exception e) {
            throw new IllegalArgumentException("Error signing SAML element: " + e.getMessage(), e);
        }
    }
Sign SAML element.

@param element the element
@param privKey the priv key
@param pubKey  the pub key
@return the element
support/cas-server-support-saml-core-api/src/main/java/org/apereo/cas/support/saml/util/AbstractSamlObjectBuilder.java