Last active
December 18, 2015 09:19
-
-
Save simpleton/5760070 to your computer and use it in GitHub Desktop.
build facebook signed request in hmac-sha256 method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://en.wikipedia.org/wiki/Base64#URL_applications | |
//http://stackoverflow.com/questions/11106393/url-safe-base64-in-objective-c | |
//http://stackoverflow.com/questions/10812140/facebook-signed-request-for-ios-hmac-sha256 | |
public class RequestMaker { | |
private static final String KEY = "testkey"; | |
private static final int BASE64_FLAG = Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING | Base64.NO_CLOSE; | |
public RequestMaker() { | |
} | |
public String getRequestPayload(String token, String user_id, String expires) { | |
return new String(Base64.encode(jsonBuilder(token, user_id, expires).getBytes(), BASE64_FLAG)); | |
} | |
public String getRequestHash(String token, String user_id, String expires) { | |
return getHmacSHA256(getRequestPayload(token, user_id, expires)); | |
} | |
public String getRequest(String token, String user_id, String expires) { | |
return getRequestHash(token, user_id, expires) + "." + getRequestPayload(token, user_id, expires); | |
} | |
private String getHmacSHA256(String str, String key) { | |
String retVal = null; | |
try { | |
Mac mac = Mac.getInstance("HmacSHA256"); | |
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm()); | |
mac.init(secret); | |
byte[] digest = mac.doFinal(str.getBytes()); | |
retVal = Base64.encodeToString(digest, BASE64_FLAG); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return retVal; | |
} | |
private String getHmacSHA256(String str) { | |
return getHmacSHA256(str, KEY); | |
} | |
private String jsonBuilder(String token, String user_id, String expires) { | |
JSONObject json = new JSONObject(); | |
try { | |
json.put("expires", expires); | |
json.put("user_id", user_id); | |
json.put("algorithm", "HMAC-SHA256"); | |
json.put("oauth_token", token); | |
} catch (JSONException jsone) { | |
jsone.printStackTrace(); | |
} | |
return json.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment