Sign Key HMAC SHA1 with Javascript

和自甴很熟 提交于 2019-12-11 03:15:48

问题


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?


回答1:


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=



来源:https://stackoverflow.com/questions/30379084/sign-key-hmac-sha1-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!