jsSHA, CryptoJS and OpenSSL libraries giving different results

淺唱寂寞╮ 提交于 2019-12-30 05:05:50

问题


New to JS, I'm also learning to use crypto libraries. I don't understand why signing/encoding the same message with the same secret yields differing results.

I'm using jsSHA 1.3.1 found here, and CryptoJS 3.0.2 described here trying to create a base64 sha-1 encoded hmac signature. Here's the code:

In html...

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

And in js...

var message = "shah me";
var secret = "hide me";
var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64) + '=';

var shaObj = new jsSHA(message, "ASCII");
var jssha = shaObj.getHMAC(secret, "ASCII", "B64") + '=';

return  "crypto answer is " + crypto + " jssha answer is " + jssha;

Can you help me explain why these results differ?

crypto answer is 3e929e69920fb7d423f816bfcd6654484f1f6d56= jssha answer is PpKeaZIPt9Qj+Ba/zWZUSE8fbVY=

What's more, both of these differ with the signature I'm generating in rails, like this...

digest  = OpenSSL::Digest::Digest.new('sha1')
raw_signature = OpenSSL::HMAC.digest(digest, "hide me","shah me")
b64_signature = Base64.encode64(raw_signature).strip

(would have liked to supply a fiddle, which seems to be a very good common practice, but that, too, is new to me and I was unable to get one working for this question).

Thanks in advance.


回答1:


There are 3 errors in your code :)

You're missing the enc-base64-min.js for crypto-js. Without it, CryptoJS.enc.Base64 will be undefined
You're missing a parameter when calling .getHMAC(). It's .getHMAC(secret, secret_type, hash_type, output_encoding)
With 1+2 adding a = isn't necessary (nor right)

<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 = "shah me";
var secret = "hide me";
var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64);
var shaObj = new jsSHA(message, "ASCII");
var jssha = shaObj.getHMAC(secret, "ASCII", "SHA-1", "B64");

return  "crypto answer is " + crypto + " jssha answer is " + jssha;

Example



来源:https://stackoverflow.com/questions/13671632/jssha-cryptojs-and-openssl-libraries-giving-different-results

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