@Override public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes = keyString.getBytes(OAuth.ENCODING); SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key); String sbs = new SignatureBaseString(request, requestParams).generate(); OAuth.debugOut("SBS", sbs); byte[] text = sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch (GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch (UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } } }
@Test public void shouldComputeCorrectHmacSha256Signature() throws Exception { // based on the reference test case from // http://oauth.pbwiki.com/TestCases OAuthMessageSigner signer = new HmacSha256MessageSigner(); signer.setConsumerSecret(CONSUMER_SECRET); signer.setTokenSecret(TOKEN_SECRET); HttpRequest request = mock(HttpRequest.class); when(request.getRequestUrl()).thenReturn("http://photos.example.net/photos"); when(request.getMethod()).thenReturn("GET"); HttpParameters params = new HttpParameters(); params.putAll(OAUTH_PARAMS); params.put("file", "vacation.jpg"); params.put("size", "original"); assertEquals("0gCtTYQAxqCKhIE0sltgx7UgHkAs10vrpuYE7xpRBnE=", signer.sign(request, params)); } }