使用Javascript签署密钥HMAC SHA1

时间:2015-05-21 16:11:17

标签: javascript google-maps-api-3 utf-8 base64 cryptojs

由于某种原因,我无法从JS中的私钥创建签名。使用谷歌的在线帮助:

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

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

示例键(为练习目的而假) 密钥:QNade5DtdJKKZbidTsrIgONupc4 =

(结果)签名:XDsiH5JAY7kJLgA1K2PWlhTdO1k =

但是,我的javascript代码:

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)

给我一​​个签名:

bOenVNeXI6xI1xlSa77oqGKssyY =

我似乎无法弄清楚我做错了什么。我是否错误地解码了base64?

1 个答案:

答案 0 :(得分:0)

为了记录,这有效:

<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)

给我:

XDsiH5JAY7kJLgA1K2PWlhTdO1k =