Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
hmac token creation
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AuthorizationMacHeader {
private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
private static final String AUTHORIZATION_HEADER_PREFIX = "HMAC-SHA256 ";
private static final String KEY_ID_LABEL = "keyid";
private static final String NONCE_LABEL = "nonce";
private static final String TS_LABEL = "ts";
private static final String BODY_HASH_LABEL = "bodyhash";
private static final String SIGNATURE_LABEL = "signature";
private static final String UTF8_ENCODING = "UTF-8";
/**
* @param key_id
* : Your key id
* @param secret_key
* : Your secret key
* @param resourcePath
* : Resource path of the API
* @param host
* : Host name of the API
* @param payload
* : payload
* @return
* @throws Exception
*/
public static final String generateHMacHeader(String key_id, String secret_key, String resourcePath,
String host, String payload) throws Exception {
// ts using time in milliseconds
String ts = String.valueOf(((long) System.currentTimeMillis()));
// nonce must be unique for each request
String nonce = UUID.randomUUID().toString();
// create the bodyHash value by hashing the payload and encoding it
SecretKeySpec signingKey = new SecretKeySpec(secret_key.getBytes(UTF8_ENCODING),
HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
byte[] rawBodyHash = mac.doFinal(payload.getBytes(UTF8_ENCODING));
String bodyHash = Base64.encodeBase64String(rawBodyHash);
// base string - this string will be used to generate mac signature.
StringBuilder baseString = new StringBuilder();
/*
* The order is CRITICAL! And no "\n" at the end.
*
* Timestamp + \n + nonce + \n+ httpmethod + \n +
* host + \n + path + \n + bodyHash
*/
String newline = "\n";
baseString.append(ts).append(newline).append(nonce).append(newline)
.append(host).append(newline).append(resourcePath).append(newline)
.append(bodyHash);
// Generate signature using client secret (crypto initialized above)
byte[] signatureBytes = mac.doFinal(baseString.toString().getBytes(UTF8_ENCODING));
// now encode the cypher for the web
String signatureStr = Base64.encodeBase64String(signatureBytes);
StringBuilder headerStringBuilder = new StringBuilder();
String authorizationHeader =
headerStringBuilder.append(AUTHORIZATION_HEADER_PREFIX).
append(KEY_ID_LABEL).append("=").append(key_id).
append(",").append(TS_LABEL).append("=").append(ts).
append(",").append(NONCE_LABEL).append("=").append(nonce).
append(",").append(BODY_HASH_LABEL).append("=").append(bodyHash).
append(",").append(SIGNATURE_LABEL).append("=").append(signatureStr).
toString();
return authorizationHeader;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment