Created
February 28, 2011 20:11
-
-
Save mpobrien/847944 to your computer and use it in GitHub Desktop.
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
//Some necessary imports | |
import java.net.URLEncoder; | |
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Hex; | |
... | |
public static String generateTypekitPreviewSignature(String apiToken, String apiTokenPublicId, String host, long timeToExpire){ | |
try{ | |
String DELIM= "\n"; | |
long expiration = (System.currentTimeMillis()/1000) + timeToExpire; | |
StringBuilder raw = new StringBuilder(""); | |
raw.append(apiTokenPublicId).append(DELIM).append("endpoint=/previewkits").append(DELIM).append("referrer=" + host).append(DELIM).append("time=" + Long.toString(expiration)); | |
String toSign = raw.toString(); | |
String sig = hmacsha256(apiToken, toSign); | |
StringBuilder result = new StringBuilder(""); | |
result.append("1").append(DELIM).append(toSign).append(DELIM).append(sig); | |
return URLEncoder.encode(result.toString(), "UTF-8"); | |
}catch(Exception e){ //unsupportedencoding, invalidkey, nosuchalgorithm | |
log.error("Couldn't generate typekit signature", e); | |
return null; | |
} | |
} | |
public static String hmacsha256(String key, String toSign){ | |
try{ | |
SecretKeySpec signingkey = new SecretKeySpec(key.getBytes(), "HmacSha256"); | |
Mac mac = Mac.getInstance("HmacSha256"); | |
mac.init(signingkey); | |
byte[] rawhmac = mac.doFinal(toSign.getBytes()); | |
return new String(Hex.encodeHex(rawhmac)); | |
} catch(Exception e){ //invalidkey, nosuchalgorithm - never gonna happen) | |
log.error("Couldn't generate hmacsha256", e); | |
return null; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment