public static String sign ( String httpMethod , String url , Map < String , String [ ] > params , String apiKey , String apiSecret , String oauthToken , String tokenSecret ) { try { if ( httpMethod != null && url != null && ! url . trim ( ) . isEmpty ( ) && params != null && apiSecret != null ) { Map < String , String [ ] > paramMap = new TreeMap <> ( params ) ; String keyString = percentEncode ( apiSecret ) + "&" + percentEncode ( tokenSecret ) ; byte [ ] keyBytes = keyString . getBytes ( Config . DEFAULT_ENCODING ) ; SecretKey key = new SecretKeySpec ( keyBytes , "HmacSHA1" ) ; Mac mac = Mac . getInstance ( "HmacSHA1" ) ; mac . init ( key ) ; addRequiredParameters ( paramMap , apiKey , oauthToken ) ; String sbs = httpMethod . toUpperCase ( ) + "&" + percentEncode ( normalizeRequestUrl ( url ) ) + "&" + percentEncode ( normalizeRequestParameters ( paramMap ) ) ; logger . debug ( "Oatuh1 base string: {}" , sbs ) ; byte [ ] text = sbs . getBytes ( Config . DEFAULT_ENCODING ) ; String sig = Utils . base64enc ( mac . doFinal ( text ) ) . trim ( ) ; logger . debug ( "Oauth1 Signature: {}" , sig ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "OAuth " ) ; // add the realm parameter, if any if ( paramMap . containsKey ( "realm" ) ) { String val = paramMap . get ( "realm" ) [ 0 ] ; sb . append ( "realm=\"" . concat ( val ) . concat ( "\"" ) ) ; sb . append ( ", " ) ; } Map < String , SortedSet < String > > oauthParams = getOAuthParameters ( paramMap ) ; TreeSet < String > set = new TreeSet <> ( ) ; set . add ( percentEncode ( sig ) ) ; oauthParams . put ( "oauth_signature" , set ) ; Iterator < String > iter = oauthParams . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String param = iter . next ( ) ; SortedSet < String > valSet = oauthParams . get ( param ) ; String value = ( valSet == null || valSet . isEmpty ( ) ) ? null : valSet . first ( ) ; String headerElem = ( value == null ) ? null : param + "=\"" + value + "\"" ; sb . append ( headerElem ) ; if ( iter . hasNext ( ) ) { sb . append ( ", " ) ; } } String header = sb . toString ( ) ; logger . debug ( "OAuth1 signed header: {}" , header ) ; return header ; } } catch ( Exception e ) { logger . error ( null , e ) ; } return null ; }
Sign a request and return the Authorization header .