  private String buildRedirectAuthnRequest(AuthnRequestType authnRequest, String relayState, boolean sign,
                                           PrivateKey key, Algorithm algorithm) throws SAMLException {
    try {
      byte[] xml = marshallToBytes(PROTOCOL_OBJECT_FACTORY.createAuthnRequest(authnRequest), AuthnRequestType.class);
      String encodedResult = deflateAndEncode(xml);
      String parameters = "SAMLRequest=" + URLEncoder.encode(encodedResult, "UTF-8");
      if (relayState != null) {
        parameters += "&RelayState=" + URLEncoder.encode(relayState, "UTF-8");
      }

      if (sign && key != null && algorithm != null) {
        Signature signature;
        parameters += "&SigAlg=" + URLEncoder.encode(algorithm.uri, "UTF-8");
        signature = Signature.getInstance(algorithm.name);
        signature.initSign(key);
        signature.update(parameters.getBytes(StandardCharsets.UTF_8));

        String signatureParameter = Base64.getEncoder().encodeToString(signature.sign());
        parameters += "&Signature=" + URLEncoder.encode(signatureParameter, "UTF-8");
      }

      return parameters;
    } catch (Exception e) {
      // Not possible but freak out
      throw new SAMLException(e);
    }
  }