0

I'm using the jsSHA library to hash passwords but I'm getting different hashes, from the same string, everytime I run the script:

/* Password hash function */
var b = $("form#register"),
    shaObj  = new jsSHA('SHA-512', 'TEXT');

b.on('submit', function (e) {

    e.preventDefault();

    var p = $('#reg_pwd'),
        q = $('#confirm_pwd');

    shaObj.update(p.val());
    var p_hash = shaObj.getHash("HEX");
    //p.val(p_hash);

    shaObj.update(q.val());
    var q_hash = shaObj.getHash("HEX");
    //q.val(q_hash);

    $('p').html('String: ' + p.val() + '<br />Hash: ' + p_hash +
                '<br />String: ' + q.val() + '<br />Hash: ' + q_hash)

    //this.submit()

});

I've been able to reproduce this in a fiddle. Just type any text in one of the fields and press submit many times to see the hash changing. It's working fine in the demo page, though.

What is going on?

Chazy Chaz
  • 1,781
  • 3
  • 29
  • 48
  • 1
    You likely need to instantiate a new instance of the object each time. Calling update on the same object likely keeps the previous input around. (I'm guessing). Additionally using SHA for passwords is not secure. Adding a salt helps but still isn't fool-proof. You should use bcrypt for passwords and you should do it server side. – Cfreak Jun 03 '16 at 04:19
  • That was the problem, thanks! Do you know any other library that is more user friendly? – Chazy Chaz Jun 03 '16 at 04:25

1 Answers1

1

jsSHA's .update() method appends additional data after any previous updates, effectively concatenating them together:

shaObj.update(p.val());
shaObj.update(q.val());
// similar to...
shaObj.update(p.val() + q.val());

To calculate hashes for each input, you'll have to create a new jsSHA() instance for each:

var shaObj = new jsSHA('SHA-512', 'TEXT'); // <---
shaObj.update(p.val());
var p_hash = shaObj.getHash("HEX");
//p.val(p_hash);

var shaObj = new jsSHA('SHA-512', 'TEXT'); // <---
shaObj.update(q.val());
var q_hash = shaObj.getHash("HEX");
//q.val(q_hash);
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Thanks, I was thinking about that but didn't tried it... Do you know any other library that is more user friendly? – Chazy Chaz Jun 03 '16 at 04:26
  • @ChazyChaz [Most hashing libraries](https://stackoverflow.com/questions/18338890/) will typically use 3 separate steps, [with `update` in the middle](http://crypto.stackexchange.com/q/9193/). It's a common model that allows for working with chunked data, streams, etc. – Jonathan Lonowski Jun 03 '16 at 05:10
  • I didn't know about those uses, and if it's common then I'll stick with it, thanks again. – Chazy Chaz Jun 03 '16 at 14:02