重力形式签名 - 从 PHP 到 java

Gravity Forms Signature - From PHP to java

来自外部应用程序的所有请求都通过检查过期签名进行身份验证。这类似于 Amazon 用于保护对其 S3 存储的访问的方法 API。一旦通过身份验证,将使用标准的 WordPress 和 Gravity Forms 基于角色的授权来确保允许 API 请求得到满足。

每个请求至少必须包含以下 3 个查询参数:

api_key - The public API key defined on the settings page e.g. "1234"
expires - Expiration date for the request expressed as a UNIX timestamp in seconds e.g. 1369749344
signature - A URL-encoded, base64 HMAC-SHA1 hash of a colon separated string following this structure:
{api_key}:{http method}:{route}:{expires}
e.g. 1234:GET:forms/1/entries:1369749344
The signature for this request using the private key of "abcd" is uJEnk0EoQ4d3iinjFMBrBzZfH9w%3D

在PHP中生成签名的示例代码,但在JAVA

中需要
  <?php
function calculate_signature($string, $private_key) {
    $hash = hash_hmac("sha1", $string, $private_key, true);
    $sig = rawurlencode(base64_encode($hash));
    return $sig;
}

$api_key = "1234";
$private_key = "abcd";
$method  = "GET";
$route    = "forms/1/entries";
$expires = strtotime("+60 mins");
$string_to_sign = sprintf("%s:%s:%s:%s", $api_key, $method, $route, $expires);
$sig = calculate_signature($string_to_sign, $private_key);
var_dump($sig);
?>

我写了这段代码,但它没有给我一个有效的签名

 public static void main(String[] args) throws Exception {
    Date d = new Date();
    int expire = 3600;
    int unixtime = (int) (d.getTime() / 1000);
    int future_unixtime = unixtime + expire;

    System.out.println(future_unixtime);

    String api_key = "1234";
    String private_key = "1345";
    String method = "GET";
    String route = "forms/1/entries";
    String stringToSign = api_key + ":" + method + ":" + route + ":" + future_unixtime;

    String output = calculateRFC2104HMAC(stringToSign, private_key);

    System.out.println(output);
}

public static String calculateRFC2104HMAC(String data, String key) throws Exception{
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    String output = new String(Base64.getEncoder().encode(mac.doFinal(data.getBytes()))).trim();
    return java.net.URLEncoder.encode(output, "UTF-8");
}

PLZ 帮帮我!

这里是 Java

的一些解决方案
public class GravityManager {

public static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException {

    SecretKey secretKey = null;

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(secretKey);

    byte[] text = baseString.getBytes();

    return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}

}