Search code examples
javascriptsha1cryptojs

Javascript : CryptoJS object missing SHA1 method


This should be easy to solve....

My CryptoJS object exists, but it doesn't have a SHA1 method.

What do I have to do to make this work? There are many many samples out there. Mine, of course, doesn't work...

The .enc.Hex.stringify method DOES exist...

Any help appreciated.

<!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        link href="blaw blaw blaw" rel="stylesheet" >
    </head>
    <body>
        content blaw blaw blaw

       <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/core.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/enc-hex.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac-sha1.js"></script>

       <script type="text/javascript">

           var StringToSign = "blaw blaw blaw";
           var hash = CryptoJS.SHA1(StringToSign); // <--- No SHA1 method!

           var result = CryptoJS.enc.Hex.stringify(hash);
           $(".content .z-value").html(result);
        </script>

Thanks


Solution

  • You have to include sha1.js before loading hmac-sha1.js, because it doesn't load it automatically (at least not in the browser). The same is true for hmac.js. Also, enc-hex.js is already included in core.js.

    Example code:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
       <div class="content"></div>
    
       <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/core.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/sha1.js"></script>
    
       <script type="text/javascript">
    
           var StringToSign = "blaw blaw blaw";
           var hash = CryptoJS.SHA1(StringToSign);
    
           var result = CryptoJS.enc.Hex.stringify(hash);
           $(".content").html(result);
        </script>
      </body>
    </html>