I am using the implementation example for two-legged authentication. Based on the Absolute minimum code to get a valid oauth_signature populated in Java or Groovy? implementation. However, I have a problem when the secret key has the character "#", I will exemplify.
For this test data, it works perfectly ..
nonce = 54408462
timestamp = 1589925486
url https://test.com/test
secretKey: Test123
key: test
generated signature: 19Cuj9dwWFmROc3Snxg5awltK10=
However when it has a character "#"...
nonce = 92475502
timestamp = 1589925554
url https://test.com/test
secretKey: Test#123
key: test
generated signature: 87QlLaFOZRsMMkJq3FGozFRNdJ0=
signature that should have been generated: OUl0yBF5sBv3/0uB0YIoTRPnrCM=
seems to me to be something of encoding, but I can't get it right
public String buildAuthorization(String url) {
String oauth_nonce = "" + (int) (Math.random() * 100000000);
String oauth_timestamp = "" + (System.currentTimeMillis() / 1000);
List<BasicNameValuePair> qparams = new ArrayList<>();
qparams.add(new BasicNameValuePair(OAUTH_CONSUMER_KEY, key));
qparams.add(new BasicNameValuePair(OAUTH_NONCE, oauth_nonce));
qparams.add(new BasicNameValuePair(OAUTH_SIGNATURE_METHOD, HMAC_SHA_1));
qparams.add(new BasicNameValuePair(OAUTH_TIMESTAMP, oauth_timestamp));
qparams.add(new BasicNameValuePair(OAUTH_VERSION, "1.0"));
String signature = "";
try {
signature = getSignature(URLEncoder.encode(url, "UTF-8"), secret,
URLEncoder.encode(URLEncodedUtils.format(qparams, "UTF-8"), "UTF-8"));
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException io) {
throw new RuntimeException("Error");
}
return "OAuth "+OAUTH_CONSUMER_KEY+"=\"" + key + "\"," +
OAUTH_SIGNATURE_METHOD+"=\"HMAC-SHA1\"," +
OAUTH_TIMESTAMP+"=\"" + oauth_timestamp + "\"," +
OAUTH_NONCE+"=\"" + oauth_nonce + "\"," +
OAUTH_VERSION+"=\"1.0\"," +
OAUTH_SIGNATURE + "=\"" + signature + "\"";
}
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class OAuthPassword {
private static final String HMAC_SHA1 = "HmacSHA1";
private static final String ENC = "UTF-8";
private static Base64 base64 = new Base64();
public static String getSignature(String url, String secret, String params)
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException {
StringBuilder base = new StringBuilder();
base.append("POST&");
base.append(url);
base.append("&");
base.append(params);
byte[] keyBytes = (secret + "&").getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
return new String(base64.encode(mac.doFinal(base.toString().getBytes(
ENC))), ENC).trim();
}
}