Created
August 9, 2016 13:45
-
-
Save rupzme/a106fb05e502b78f05058f3ca006960b to your computer and use it in GitHub Desktop.
Java Create HMAC
This file contains 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
import java.net.URLEncoder; | |
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Base64; | |
/** | |
* Sign an unsigned URL. | |
* @param path The URL-encoded path including the leading slash. E.g. "/1.0/account/1/2". | |
* @param key The access key id of the secret access key to use for creating the | |
* signature. | |
* @param expires The time in seconds from the Epoch when the signature expires. | |
* @param key The secret access key to use for creating the signature. | |
* @return the URL-encoded path with the signature query string added to the end. | |
*/ | |
public static String sign(String path, String accesKeyId, Long expires, String key) throws Exception { | |
// Create the canonical string from expires and path | |
String canonical = "GET\n\n\n" + expires + "\n" + path; | |
// Encrypt it with key | |
byte[] keyBytes = Base64.decodeBase64(key.getBytes("US-ASCII")); | |
Mac hmac = Mac.getInstance("HmacSHA256"); | |
hmac.init(new SecretKeySpec(keyBytes, "HmacSHA256")); | |
byte[] signatureBytes = hmac.doFinal(canonical.getBytes("UTF-8")); | |
// Base64 encode the encrypted results | |
String signatureBase64 = new String(Base64.encodeBase64(signatureBytes), "US-ASCII"); | |
// URL encode the base64 | |
String signature = URLEncoder.encode(signatureBase64, "UTF-8"); | |
// Assemble the signed URL | |
return path + "?a1accesskeyid=" + accesKeyId + "&expires="+ expires + "&signature=" + signature; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment