Ilia Karmanov
Ilia Karmanov

Reputation: 215

Sign Key HMAC SHA1 with Javascript

For some reason I am not able to create a signature from a private key in JS. Using this online help from google:

https://m4b-url-signer.appspot.com/

URL:https://google.maps.com/maps/api/geocode/json?address=New+York&client=test

Example Key (fake for the purposes of the exercise) Key: QNade5DtdJKKZbidTsrIgONupc4=

(Result) Signature: XDsiH5JAY7kJLgA1K2PWlhTdO1k=

However, my javascript code:

var keyString = 'QNade5DtdJKKZbidTsrIgONupc4=';
    console.log(keyString)

var urlString = encodeURIComponent('/maps/api/geocode/json?address=New+York&client=test');
console.log(urlString)

// We need to decode private key to binary
var decoded_key_words = CryptoJS.enc.Utf8.parse(keyString);
var decoded_key = CryptoJS.enc.Base64.stringify(decoded_key_words);

console.log(decoded_key);

var signature = CryptoJS.HmacSHA1(decoded_key,urlString);
console.log(signature);

//  Encode binary signature to base 64
var encoded_signature = CryptoJS.enc.Base64.stringify(signature);
console.log(encoded_signature)

Gives me a signature:

bOenVNeXI6xI1xlSa77oqGKssyY=

I can't seem to figure out what I'm doing wrong. Am I decoding base64 incorrectly?

Upvotes: 3

Views: 3064

Answers (1)

Ilia Karmanov
Ilia Karmanov

Reputation: 215

For the record, this worked:

<script src="sha.js"></script>

var url = '/maps/api/geocode/json?address=New+York&client=test';
var key = 'QNade5DtdJKKZbidTsrIgONupc4='

var hmacObj = new jsSHA(url, 'TEXT');
var hmacOutput = hmacObj.getHMAC(key,'B64','SHA-1','B64');

console.log(hmacOutput)

Giving me:

XDsiH5JAY7kJLgA1K2PWlhTdO1k=

Upvotes: 1

Related Questions