1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public static String encode(String key, String data) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8"))); }
public static void main(String [] args) throws Exception { System.out.println(encode("key", "The quick brown fox jumps over the lazy dog")); }
void createSignature(String accessKey, String secretKey, String method, String host, String uri, UrlParamsBuilder builder) { StringBuilder sb = new StringBuilder(1024);
if (accessKey == null || "".equals(accessKey) || secretKey == null || "".equals(secretKey)) { throw new MyApiException(MyApiException.KEY_MISSING, "API key and secret key are required"); }
sb.append(method.toUpperCase()).append('\n') .append(host.toLowerCase()).append('\n') .append(uri).append('\n');
builder.putToUrl(accessKeyId, accessKey) .putToUrl(signatureVersion, signatureVersionValue) .putToUrl(signatureMethod, signatureMethodValue) .putToUrl(timestamp, gmtNow());
sb.append(builder.buildSignature()); Mac hmacSha256; try { hmacSha256 = Mac.getInstance(signatureMethodValue); SecretKeySpec secKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), signatureMethodValue); hmacSha256.init(secKey); } catch (NoSuchAlgorithmException e) { throw new MyApiException(MyApiException.RUNTIME_ERROR, "[Signature] No such algorithm: " + e.getMessage()); } catch (InvalidKeyException e) { throw new MyApiException(MyApiException.RUNTIME_ERROR, "[Signature] Invalid key: " + e.getMessage()); } String payload = sb.toString(); byte[] hash = hmacSha256.doFinal(payload.getBytes(StandardCharsets.UTF_8));
String actualSign = Base64.getEncoder().encodeToString(hash);
builder.putToUrl(signature, actualSign);
}
|