The api_sig is to be appended to the URL for all such API calls. The following code can be used to generate the api_sig (of course, you can use a higher-level library such as flickrj if you enjoy eating microwave ready to eat meals over growing your own tomatoes ;-).
package com.jasondchambers.flickr;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Generates an api_sig from a list of parameter key value pairs
*
* The signing process goes like this. The parameters are sorted
* e.g. foo=1, bar=2, baz=3 sorts to bar=2, baz=3, foo=1
* The secret and the parameters are concatenated together as follows to provide
* the raw signature
* e.g. SECRETbar2baz3foo1
* An MD5 hash is created, converted to hex and returned - this is to be used as
* the api_sig parameter
*
* See section 8 of [1]
*
* [1] http://www.flickr.com/services/api/auth.spec.html
*
* @author Jason Chambers
*
*/
public class ApiSigGenerator {
private String secret;
public ApiSigGenerator(String secret) {
this.secret = secret;
}
public String sign(String... paramKeyValuePairs) {
try {
// Sort the parameters first
SortedMap<String, String> sortedParameterMap = sort(paramKeyValuePairs);
// Generate the raw signature
String rawApiSig = generateRawApiSig(sortedParameterMap);
// Hash the raw signature and return
return generateMd5(rawApiSig.toString());
}
catch (Exception e) {
throw new FlickrClientException(e);
}
}
private SortedMap<String, String> sort(String[] paramKeyValuePairs) {
SortedMap<String, String> sortedParameterMap = new TreeMap<String, String>();
final int KEY = 0;
final int VALUE = 1;
int i = KEY;
String key = null;
for (String o : paramKeyValuePairs) {
if (i == KEY) {
key = o;
} else {
sortedParameterMap.put(key, o);
}
i = ~i;
}
return sortedParameterMap;
}
private String generateRawApiSig(SortedMap<String, String> sortedParameterMap) {
StringBuffer rawApiSig = new StringBuffer();
rawApiSig.append(secret);
Set<String> keySet = sortedParameterMap.keySet();
for (String k1 : keySet) {
rawApiSig.append(k1);
rawApiSig.append(sortedParameterMap.get(k1));
}
return rawApiSig.toString();
}
private static String generateMd5(String input) throws NoSuchAlgorithmException {
StringBuffer output = new StringBuffer();
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5 = md.digest(input.getBytes());
for (int i = 0; i < md5.length; i++) {
String tmpStr = "0" + Integer.toHexString((0xff & md5[i]));
output.append(tmpStr.substring(tmpStr.length() - 2));
}
return output.toString();
}
}

0 comments:
Post a Comment