Skip to content

Instantly share code, notes, and snippets.

@kientux
Last active March 21, 2017 06:52
Show Gist options
  • Save kientux/0a2e9fb359c21a8993b19519a9841936 to your computer and use it in GitHub Desktop.
Save kientux/0a2e9fb359c21a8993b19519a9841936 to your computer and use it in GitHub Desktop.
protected Map<String, String> buildRequestParameters(Const.HttpMethod httpMethod, String requestPath,
SyncStore store) {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("oauth_consumer_key", store.getConsumerKey());
params.put("oauth_nonce", generateOAuthNonce(32));
params.put("oauth_signature_method", "HMAC-SHA1");
params.put("oauth_timestamp", String.valueOf(System.currentTimeMillis() / 1000L));
String signature = buildOAuthSignature(httpMethod.name(), requestPath, params, store.getConsumerSecret());
params.put("oauth_signature", signature);
return params;
}
private String generateOAuthNonce(int length) {
return RandomStringUtils.randomAlphanumeric(length);
}
private String buildOAuthSignature(String httpMethod, String requestUri, Map<String, String> params, String secret) {
try {
String encodedRequestUri = URLEncoder.encode(requestUri, "UTF-8");
ArrayList<String> encodedParams = new ArrayList<String>();
for (String key : params.keySet()) {
String encodedKey = URLEncoder.encode(key, "UTF-8");
String encodedValue = URLEncoder.encode(params.get(key), "UTF-8");
encodedParams.add(encodedKey + "=" + encodedValue);
}
String paramsString = StringUtils.join(encodedParams, "&");
String encodedParamsString = URLEncoder.encode(paramsString, "UTF-8");
String stringToSign = httpMethod + "&" + encodedRequestUri + "&" + encodedParamsString;
log.info("String to sign: " + stringToSign);
String signature = calculateRFC2104HMAC(stringToSign, secret + "&");
return URLEncoder.encode(signature, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String calculateRFC2104HMAC(String data, String key)
throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
String alg = "HmacSHA1";
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), alg);
Mac mac = Mac.getInstance(alg);
mac.init(signingKey);
return hmacToString(mac.doFinal(data.getBytes()));
}
private static String hmacToString(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment