michael
michael

Reputation: 4483

Use Javascript to confirm a hash made in PHP?

I need a way of creating a hash in PHP (crypt() or md5()) that can be replicated by Javascript.

Ie.

  1. Create a hash of "hello world" using PHP (using prearranged private salt)
  2. Put the hash and the plain text in two hidden form fields
  3. Form gets submitted via ajax to a Node.js server
  4. Use Javascript to repeat the hashing on the plain text (again with private salt) and check if the hashes match

Is there a native function in JS or a common (reliable) 3rd party script that I can use to accomplish this? I'd rather not invoke PHP from the Node server.

Upvotes: 2

Views: 854

Answers (1)

Kevin Hakanson
Kevin Hakanson

Reputation: 42210

In the browser, you could use CryptoJS to create an HMAC (Hash-based Message Authentication Code). The challenge will be distributing your "prearranged private salt."

Here is the sample code from the CryptoJS documentation:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-md5.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha512.js"></script>
<script>
    var hash = CryptoJS.HmacMD5("Message", "Secret Passphrase");
    var hash = CryptoJS.HmacSHA1("Message", "Secret Passphrase");
    var hash = CryptoJS.HmacSHA256("Message", "Secret Passphrase");
    var hash = CryptoJS.HmacSHA512("Message", "Secret Passphrase");
</script>

On Node.js, use the Crypto module:

require("crypto")
  .createHmac("sha256", "Secret Passphrase")
  .update("Message")
  .digest("base64");

Upvotes: 1

Related Questions