Coinbase API认证总是无效的Java签名



我一直在尝试用Java在Coinbase API上验证自己。这几天我一直在寻找我的错误,但是没有找到。我总是收到无效签名错误。我创建签名的方法如下所示:

public static String createSignature(String secret, String time, String method,String uri, String body) throws URISyntaxException, JSONException {
String keyspec = org.apache.commons.codec.digest.DigestUtils.sha256Hex(secret);
System.out.println("Keyspec: " + keyspec);
String prehash = time + method.toUpperCase() + uri + body;
String sign = Base64.getEncoder().encodeToString(org.apache.commons.codec.digest.DigestUtils.sha256(prehash.getBytes()));
System.out.println("Signature: " + sign);
return sign;
}

我这样调用这个方法:

String path = "https://api.coinbase.com/v2/user";
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(path))
.headers("CB-ACCESS-KEY","my_access_key","CB-ACCESS-SIGN",createSignature("my_secret_key", path, "GET",currTime,""),"CB-ACCESS-TIMESTAMP",currTime)
.GET()
.build();

我还从Coinbase API获得当前纪元时间,因此我的PC和服务器的时间之间不应该存在差异。提前感谢!

试试这个:

private HttpHeaders prepareHeaders(String method, String path, String body) throws Exception {
Timestamp timestamp = Timestamp.from(ZonedDateTime.now().toInstant());
String tsSeconds = String.valueOf(timestamp.toInstant().getEpochSecond());
var message = tsSeconds + method + path + body;
String signature = encode("HmacSHA256", coinbaseAPISecret, message);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("CB-ACCESS-KEY", coinbaseAPIKey);
headers.add("CB-ACCESS-SIGN", signature);
headers.add("CB-ACCESS-TIMESTAMP", tsSeconds);
headers.add("CB-VERSION", LocalDate.now().toString());
return headers;
}
private String encode(String algorithm, String key, String data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKeySpec);
return Hex.encodeHexString(mac.doFinal(data.getBytes()));
}

相关内容

  • 没有找到相关文章

最新更新