gpt4 book ai didi

java - 重力形式签名 - 从 PHP 到 java

转载 作者:搜寻专家 更新时间:2023-10-31 21:03:31 24 4
gpt4 key购买 nike

来自外部应用程序的所有请求都通过检查过期签名进行身份验证。这类似于 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();
}

关于java - 重力形式签名 - 从 PHP 到 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36882226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com