I have got my private key and api key,How to create HMAC signature using javascript.What actually is HMAC signature?

StackOverflow https://stackoverflow.com/questions/22909255

  •  28-06-2023
  •  | 
  •  

Вопрос

I want to create HMAC-SHA1 signature in my Sharepoint app of Indian Railways how should I create following code is not working, I mean when I copy paste my HMAC signature to URL it is giving an error, {"error":"UNAUTHORIZED ACCESS. HMAC SIGNATURE MISMATCH."}. And not displaying json, how should I achieve it following is my code.

<script src="lib/jsSHA/src/sha1.js"></script>

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha1.js"></script>

<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>



<script type="text/javascript" >



var message = "json539ff0f815ca697c681fe01d32ba52e31234567890";
        var secret = "<my private key>";


        var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64);
    //var crypto = CryptoJS.HmacSHA1(message, secret).toString();
        alert(crypto);

        var shaObj = new jsSHA(message, "ASCII");
            alert("Welcome");
        var jssha = shaObj.getHMAC(secret, "ASCII", "SHA-1", "B64");
        alert(crypto + "\n" + jssha);


</script>
Это было полезно?

Решение

HMAC is sort of hash algorithms (it counts something like CRC code for provided message but on cryptographic basis). HMAC counts hash value of the message and uses key for it. The purpose of it is to prove that the hash has been counted only by someone who knows the key and nobody else.

HMAC mismatch error can be caused by many reasons:

  1. You use wrong HMAC algorithm. In your code you use HMAC SHA1 but there are many of them
  2. You use good HMAC algorithm but wrong HMAC parameters. HMAC algorithm has typically several parameters like length, chaining mode,...
  3. You use wrong message formatting. There might be some kind of message formatting rules before you count HMAC.
  4. you use wrong key.

Другие советы

It is happening by following code,

<script src="lib/jsSHA/src/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>


var message = "mrjjson539ff0f815ca697c681fe01d32ba52e3";
var secret = "e439c4c1b7d7d2d52d11c0f1cb56552d";
//var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64);
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
//var shaObj = new jsSHA(message, "ASCII");
//var jssha = shaObj.getHMAC(secret, "ASCII", "SHA-1", "B64");

alert("crypto answer is " + crypto);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top