Subject: [OAUTH-WG] Oauth signature problem

From: Sunil Pal <[email-masked]>
Date: Thu, 12 Sep 2013 12:35:37 +0530

How to generate the correct oauth_signature in apex.Here is the code for
generating oauth_nonce, oauth_timestamp and oauth_signature. But not
getting the correct oauth_signature

// Generate a unique combination of numbers and alphabets for oauth-nonce
String nonce = String.valueOf(Crypto.getRandomLong());
Blob key = Blob.valueOf(nonce);
String Keyy = 'XXXXXXXXXXXXXXXX';
Long timee=DateTime.now().getTime();
Integer random = Crypto.getRandomInteger();
Integer time2 = integer.valueOf(timee) +random;
String str2= string.valueOf(time2);
Blob key2= Blob.valueOf(str2);
Blob keyHash = Crypto.generateDigest('MD5',key2);
String hexDigest = EncodingUtil.convertToHex(keyHash);
// Generate timestamp for current time
String timestamp = String.valueOf(DateTime.now().getTime()/1000);
// Create map for maintaining the parameters used to create signature
map<String, String> parameters = new Map<String, String>();
parameters.put('oauth_consumer_key','ZZZZZZZZZZZZ');
parameters.put('oauth_signature_method','HMAC-SHA1');
parameters.put('oauth_timestamp',timestamp);
parameters.put('oauth_nonce',hexDigest);
parameters.put('oauth_version','1.0');
// Form the gneral HttpRequest
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://YYYYYYYYYYY.com/people/1234567/identity');
String host = req.getEndpoint();
Integer n = host.indexOf('?');
List<String> keys = new List<String>();
keys.addAll(parameters.keySet());
keys.sort();
String str = keys.get(0)+'='+parameters.get(keys.get(0));
for(Integer i=1;i<keys.size();i++)
{
    str = str +'&'+keys.get(i)+'='+parameters.get(keys.get(i));
}
String s =  req.getMethod().toUpperCase()+ '&' +
			EncodingUtil.urlEncode(host, 'UTF-8') +'&'+
			EncodingUtil.urlEncode(str, 'UTF-8');
Blob sig = Crypto.generateMac('Hmac-SHA1', Blob.valueOf(s), Blob.valueOf(Keyy));
Blob signature1 = Blob.valueOf(EncodingUtil.convertToHex(sig));
String signature = EncodingUtil.base64encode(signature1);
req.setEndpoint('https://XXXXXXXXX.com/people/1234567/identity?oauth_version=1.0&oauth_nonce='+hexDigest+'&oauth_timestamp='+timestamp+'&oauth_consumer_key=ZZZZZZZZZZZZZ&oauth_signature_method=HMAC-SHA1&oauth_signature='+signature+'');
HttpResponse res = h.send(req);
System.debug('Response from request token request:
('+res.getStatusCode()+')'+res.getBody());

---
Thanks And Warm Regards
Sunil Kumar Pal