5

I'm trying to duplicate PHP's crypt() function in JavaScript with regards to generating a SHA512 hash, such as this:

$hash = crypt( $text, '$6$' . $salt );

This generates something like this:

$6$salt$hashedtext

I'm trying with CryptoJS, like this:

var hash = CryptoJS.SHA512( text );

And this does generate the SHA512 hash for me, like this:

hashedtext

But I don't see any way to supply a salt. I've never used CryptoJS before, so I'm totally novice on this.. but I've done some googling and haven't been able to locate an answer to this. Hopefully it's simple and just evading me.

How can I generate a string that matches the above-formatted string returned by the crypt() example?

Nick Coons
  • 3,682
  • 1
  • 19
  • 21
  • Are you simply trying to hash a value, or are you trying to encode a password? If you're trying to encode a password, why are you doing it client side? If you simply hash a secret and send it over the wire then the secret value is irrelevant as an attacker just has to intercept and re-send the hash. – Sammitch Nov 17 '15 at 23:33
  • Ultimately, I'm trying to create an API Token by hashing an API Key and an API Password. I'm transmitting it over SSL, so this isn't to try to enhance security, but because this is the format that the API server is expecting. I can communicate with the server using PHP, but I haven't had any luck duplicating the PHP code in JS. I can manually generate the Token and send it, and that works just fine. But I don't want to do that every time I'm given a new Key or Password. This is for a Phonegap app, so my only option is to do this client-side. – Nick Coons Nov 17 '15 at 23:46
  • Here's the code to generate the Token in PHP: `$token = $api_key . crypt( $api_pass, '$6$' . $salt );` – Nick Coons Nov 17 '15 at 23:47
  • Are *you* writing this API, or are you trying to integrate with someone else's? – Sammitch Nov 18 '15 at 00:11
  • I'm trying to integrate with someone else's, so I have no control over the back-end. – Nick Coons Nov 18 '15 at 01:27
  • Well, I've batted around this issue on and off over the course of the day. 1. `crypt()` is [far more than simple hashing](https://fossies.org/dox/glibc-2.22/sha256-crypt_8c_source.html#l00102). 2. No one seems to have written a `crypt()` lib in JavaScript because using it like this is not a good idea, and literally every other use case is 1000% worse. – Sammitch Nov 19 '15 at 00:33
  • That's true, but in the implementation in my sample code above, it is being used as a SHA512 hashing function as per the PHP docs. CryptoJS provides a SHA512 hashing function, but doesn't provide a way (that I've been able to find) to specify a salt. Thanks for your efforts. – Nick Coons Nov 20 '15 at 06:40
  • 1
    The salt is nothing more than just adding some (known) random text to the hash you're making. Then, you just concatenate the hash to the salt to say "hey, this is what I've hashed, with this salt."! :) – Alessio Periloso Feb 16 '16 at 18:48

0 Answers0