Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2005 PayPal, Inc. All Rights Reserved.
   */
  
  package com.paypal.base.util;
  
 import java.util.List;
 import java.util.Map;
 
 
 
 public class OAuthSignature {
 
 	private static final String PARAM_DELIMETER = "&";
 	private static final String PARAM_SEPERATOR = "=";
 	private static final String ENCODING = "US-ASCII";
 	private static final String SIGNATURE_METHOD = "HMAC-SHA1";
 	private static final String SIGNATURE_ALGORITHM = "HmacSHA1";
 	public static final String OAUTH_VERSION = "1.0";
 	private String consumerKey;
 	private String consumerSecret;
 	private String token;
 	private String tokenSecret;
 	private String requestURI;
 	private String timestamp;
 	private String httpMethod;
 
 	public enum HTTPMethod {
 		GET, HEAD, POST, PUT, UPDATE
 	}

Default Constructor

Parameters:
consumerKey - Consumer key shared between PayPal and Consumer (OAuth consumer)
consumerSecret - Secret shared between PayPal and Consumer (OAuth consumer)
 
 	public OAuthSignature(String consumerKeyString consumerSecret) {
 		this. = new ArrayList<Parameter>();
 		this. = consumerKey;
 		this. = consumerSecret;
 		this. = "POST";
 	}

Sets Token to be used to generate signature.

Parameters:
token - String version of Token. The token could be Access or Request
 
 	public void setToken(String token) {
 		this. = token;
 	}

Adds Parameter. Parameter could be part of URL, POST data.

Parameters:
name parameter name with no URL encoding applied
value parameter value with no URL encoding applied
 
 	public void addParameter(String nameString value) {
 		.add(new Parameter(namevalue));
 	}

Sets Token secret as received in Token response.

Parameters:
secret byte array of token secret
 
 	public void setTokenSecret(String secret) {
 		this. = secret;
 	}

Sets URI for signature computation.

Parameters:
uri - Script URI which will be normalized to scheme://authority:port/path if not normalized already.
	public void setRequestURI(String urithrows OAuthException {
		this. = normalizeURI(uri);
	}

Sets time stamp for signature computation.

Parameters:
timestamp - time stamp at which Token request sends.
	public void setTokenTimestamp(String timestamp) {
		this. = timestamp;
	}

Sets HTTP Method

Parameters:
method HTTP method used for sending OAuth request
	public void setHTTPMethod(HTTPMethod method) {
		switch (method) {
		case :
			 = "GET";
			break;
		case :
			 = "HEAD";
			break;
		case :
			 = "PUT";
			break;
		case :
			 = "UPDATE";
			break;
		default:
			 = "POST";
			break;
		}
	}

Computes OAuth Signature as per OAuth specification using signature Method. using the specified encoding scheme enc.

Returns:
the Base64 encoded string.
Throws:
com.paypal.base.exception.OAuthException if invalid arguments.
		validate(this."API UserName");
		validate(this."API Password");
		validate(this."Access Token");
		validate(this."Token Secret");
		validate(this."Request URI");
		validate(this."Timestamp");
		String signature = "";
		try {
			String key = PayPalURLEncoder.encode();
			key += PayPalURLEncoder.encode();
			params.add(new Parameter("oauth_consumer_key"this.));
			params.add(new Parameter("oauth_version"));
			params.add(new Parameter("oauth_signature_method"));
			params.add(new Parameter("oauth_token"this.));
			params.add(new Parameter("oauth_timestamp"this.));
			Collections.sort(paramsnew ParamComparator());
			String signatureBase = this. + ;
			signatureBase += PayPalURLEncoder.encode();
			signatureBase += ;
			String paramString = "";
			StringBuilder paramStringBuilder = new StringBuilder();
			Iterator<Parameterit = params.iterator();
			while (it.hasNext()) {
				Parameter current = (Parameterit.next();
				paramStringBuilder.append(current.getName())
				if (it.hasNext()) {
					paramStringBuilder.append();
				}
			}
			paramString = paramStringBuilder.toString();
			signatureBase += PayPalURLEncoder.encode(paramString);
			hmac.init(new SecretKeySpec(key.getBytes(), hmac
			hmac.update(signatureBase.getBytes());
			byte[] digest = hmac.doFinal();
			Base64 b64Encoder = new Base64();
			signature = new String(b64Encoder.encode(digest), );
catch (NoSuchAlgorithmException algoe) {
			throw new OAuthException(algoe.getMessage(), algoe);
catch (InvalidKeyException ke) {
			throw new OAuthException(ke.getMessage(), ke);
			throw new OAuthException(ee.getMessage(), ee);
		}
		return signature;
	}

Validate that the specified parameter is not null and not empty.

Parameters:
param The parameter to validate
name The name of the parameter for the exception text.
Throws:
com.paypal.base.exception.OAuthException
com.paypal.base.exception.OAuthException If the parameter is not valid.
	private void validate(String paramString namethrows OAuthException {
		if ((param == null) || (param.length() == 0)) {
			throw new OAuthException("Value is required: " + name);
		}
	}

verifyV1Signature verifies signature against computed signature.

Returns:
true if signature verified otherwise false
Throws:
com.paypal.base.exception.OAuthException in case there are any failures in signature computation.
	public boolean verifyV1Signature(String signaturethrows OAuthException {
		String signatureComputed = computeV1Signature();
		return signatureComputed.equals(signature);
	}

normalizeURI normalizes the given URI as per OAuth spec

Parameters:
uri
Returns:
normalized URI. URI normalized to scheme://authority:port/path
Throws:
com.paypal.base.exception.OAuthException
	private String normalizeURI(String urithrows OAuthException {
		String normalizedURI = ""port = ""scheme = ""path = ""authority = "";
		int ijk;
		try {
			i = uri.indexOf(':');
			if (i == -1) {
				throw new OAuthException("Invalid URI.");
else {
				scheme = uri.substring(0, i);
			}
			// find next : in URL
			j = uri.indexOf(":"i + 2);
			if (j != -1) {
				// port has specified in URI
				authority = uri.substring(scheme.length() + 3, j);
				k = uri.indexOf("/"j);
				if (k != -1) {
					port = uri.substring(j + 1, k);
else {
					port = uri.substring(j + 1);
				}
else {
				// no port specified in uri
				k = uri.indexOf("/"scheme.length() + 3);
				if (k != -1) {
					authority = uri.substring(scheme.length() + 3, k);
else {
					authority = uri.substring(scheme.length() + 3);
				}
			}
			if (k != -1) {
				path = uri.substring(k);
			}
			normalizedURI = scheme.toLowerCase(.);
			normalizedURI += "://";
			normalizedURI += authority.toLowerCase(.);
			if (scheme != null && port.length() > 0) {
				if (scheme.equalsIgnoreCase("http")
						&& Integer.parseInt(port) != 80) {
					normalizedURI += ":";
					normalizedURI += port;
else if (scheme.equalsIgnoreCase("https")
						&& Integer.parseInt(port) != 443) {
					normalizedURI += ":";
					normalizedURI += port;
				}
			}
catch (NumberFormatException nfe) {
			throw new OAuthException("Invalid URI."nfe);
		}
		normalizedURI += path;
		return normalizedURI;
	}

Inner class for sorting Collection
	private static class ParamComparator implements Comparator<Parameter>,
		private static final long serialVersionUID = 8587372068875833370L;
		public int compare(Parameter xParameter y) {
			int retval = 0;
			if (x != null && y != null) {
				retval = ((Parameterx).getName().compareTo(
						((Parametery).getName());
				// if parameter names are equal then compare parameter values.
				if (retval == 0) {
					retval = ((Parameterx).getValue().compareTo(
				}
			}
			return retval;
		}
	}

Inner class for representing Parameter
	private static class Parameter {
		public Parameter(String nameString value) {
			this. = name;
			this. = value;
		}
		public void setName(String name) {
			this. = name;
		}
		public void setValue(String val) {
			this. = val;
		}
		public String getName() {
			return this.;
		}
		public String getValue() {
			return this.;
		}
		private String mName;
		private String mValue;
	}

Accepts the required parameters and Provides OAuth signature and TimeStamp.

Parameters:
apiUserName API User name.
apiPassword API Password of user.
accessToken Obtained during Permission Request of token.
tokenSecret Obtained during Permission Request of token.
httpMethod HTTP Method (GET,POST etc.)
scriptURI API Server End Point.
queryParams Extra 'name/value' parameters if required.
Returns:
java.util.Map of HTTPHeaders
	public static Map getAuthHeader(String apiUserNameString apiPassword,
			String accessTokenString tokenSecretHTTPMethod httpMethod,
			String scriptURIMap queryParamsthrows OAuthException {
		Map headers = new HashMap();
		String consumerKey = apiUserName;
		String consumerSecretStr = apiPassword;
		String time = String.valueOf(System.currentTimeMillis() / 1000);
		OAuthSignature oauth = new OAuthSignature(consumerKey,
				consumerSecretStr);
		if (..equals(httpMethod) && queryParams != null) {
			Iterator itr = queryParams.entrySet().iterator();
			while (itr.hasNext()) {
				Map.Entry param = (Map.Entryitr.next();
				String key = (Stringparam.getKey();
				String value = (Stringparam.getValue();
				oauth.addParameter(keyvalue);
			}
		}
		oauth.setToken(accessToken);
		oauth.setTokenSecret(tokenSecret);
		oauth.setHTTPMethod(httpMethod);
		oauth.setTokenTimestamp(time);
		oauth.setRequestURI(scriptURI);
		// Compute Signature
		String sig = oauth.computeV1Signature();
		headers.put("Signature"sig);
		headers.put("TimeStamp"time);
		return headers;
	}

Computes the value of the X_PP_AUTHORIZATION header

Parameters:
apiUserName API User name.
apiPassword API Password of user.
accessToken Obtained during Permission Request of token.
tokenSecret Obtained during Permission Request of token.
httpMethod HTTP Method (GET,POST etc.)
scriptURI API Server End Point.
queryParams Extra 'name/value' parameters if required.
Returns:
Auth String
Throws:
com.paypal.base.exception.OAuthException
	public static String getFullAuthString(String apiUserName,
			String apiPasswordString accessTokenString tokenSecret,
			HTTPMethod httpMethodString scriptURIMap queryParams)
			throws OAuthException {
		Map headers = getAuthHeader(apiUserNameapiPasswordaccessToken,
				tokenSecrethttpMethodscriptURIqueryParams);
		return "token=" + accessToken + ",signature="
headers.get("Signature") + ",timestamp="
headers.get("TimeStamp");
	}
New to GrepCode? Check out our FAQ X