private String signRequest()

in plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/SAMLProcessorImpl.java [528:597]


    private String signRequest(
        FedizContext config,
        StringBuilder sb
    ) throws Exception {
        Crypto crypto = config.getSigningKey().getCrypto();
        if (crypto == null) {
            LOG.debug("No crypto instance of properties file configured for signature");
            throw new ProcessingException("Failed to Sign Request");
        }
        String signatureUser = config.getSigningKey().getKeyAlias();
        if (signatureUser == null) {
            LOG.debug("No user configured for signature");
            throw new ProcessingException("Failed to Sign Request");
        }
        String signaturePassword = config.getSigningKey().getKeyPassword();
        if (signaturePassword == null) {
            LOG.debug("No signature password available");
            throw new ProcessingException("Failed to Sign Request");
        }

        // Get the private key
        PrivateKey privateKey = crypto.getPrivateKey(signatureUser, signaturePassword);
        if (privateKey == null) {
            LOG.debug("No private key available");
            throw new ProcessingException("Failed to Sign Request");
        }

        String sigAlgo = WSConstants.RSA_SHA1;
        String jceSigAlgo = "SHA1withRSA";
        LOG.debug("automatic sig algo detection: " + privateKey.getAlgorithm());
        if ("DSA".equalsIgnoreCase(privateKey.getAlgorithm())) {
            sigAlgo = WSConstants.DSA;
            jceSigAlgo = "SHA1withDSA";
        } else {
            switch(((SAMLProtocol)config.getProtocol()).getSignRequestAlgorithm()) {
            case RSA_SHA1:
                sigAlgo = WSConstants.RSA_SHA1;
                jceSigAlgo = "SHA1withRSA";
                break;
            case RSA_SHA256:
                sigAlgo = WSConstants.RSA_SHA256;
                jceSigAlgo = "SHA256withRSA";
                break;
            default:
                throw new ProcessingException("Unknown sign algorithm");
            }
        }
        LOG.debug("Using Signature algorithm " + sigAlgo);

        // Sign the request
        Signature signature = Signature.getInstance(jceSigAlgo);
        signature.initSign(privateKey);

        sb.append('&').append(SAMLSSOConstants.SIG_ALG).append('=').append(URLEncoder.encode(sigAlgo, "UTF-8"));
        String requestToSign = sb.toString();

        signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
        byte[] signBytes = signature.sign();

        String encodedSignature = Base64.getEncoder().encodeToString(signBytes);
        
        // Clean the private key from memory when we're done
        try {
            privateKey.destroy();
        } catch (DestroyFailedException ex) {
            // ignore
        }

        return URLEncoder.encode(encodedSignature, "UTF-8");
    }