1

I hope the title is correctly defined.I am passing postal code to Google Geocoding API and required to generate signature with private key provided.I successfully generate the key based on reference in Salesforce class.I do some testing on different postal code and face this issue.Some of signature are valid but some are invalid.

This is really weird because signature is generated from the same method, how come when I pass different postal code, some of it valid but some of it not valid.

This is example of my code.I hide private key and client id.

//replace the number with any postal code to test
String baseUrl = 'https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:97008&client=gme-xxxx';
URL url = new URL(baseURL);
String path =url.getPath();
String query=url.getQuery();
String input=path+'?'+query;


System.debug('@unid path '+ path);
System.debug('@unid query '+ query);
System.debug('@unid input '+ input);

String privateKey='xxxxxxxxxxxx=';

Blob decodePK = EncodingUtil.base64Decode(privateKey);
String algorithmName = 'hmacSHA1';
Blob hmacData = Crypto.generateMac(algorithmName, Blob.valueOf(input), decodePK);
String signature =EncodingUtil.urlEncode(EncodingUtil.base64Encode(hmacData), 'UTF-8');
signature = signature.replace('+', '-');
signature = signature.replace('/', '_');

baseUrl +='&signature='+signature;

//this is the final URL that  can be pasted to browser
system.debug('@unid baseURL ='+ baseURL);

Example of postal code that not working 97015,97008 . Example of postal code that working 97005,98006,80014

Both are using the same code to generate the key.

Thanks.

1 Answer 1

1

I fixed it already.By removing + and / before executing EncodingUtil.urlEncode.

Blob hmacData = Crypto.generateMac(algorithmName, Blob.valueOf(input), decodePK);
String encodePK =EncodingUtil.base64Encode(hmacData);
encodePK = encodePK.replace('+', '-');
encodePK = encodePK.replace('/', '_');
String signature =EncodingUtil.urlEncode(encodePK, 'UTF-8');
signature = signature.replace('+', '-');
signature = signature.replace('/', '_');
baseUrl +='&signature='+signature;
1
  • Yep, that's base64url encoding.
    – metadaddy
    Commented Oct 27, 2014 at 22:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .