Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
MessageVerifier implementation for node.js
crypto = require 'crypto'
MessageVerifier =
serializer: JSON.stringify
deserializer: JSON.parse
generate: (data, secret, algorithm) ->
algorithm ?= 'sha1'
base64 = (new Buffer(MessageVerifier.serializer(data))).toString('base64')
hmac = crypto.createHmac(algorithm, secret)
verify: (message, secret, algorithm) ->
algorithm ?= 'sha1'
[data, signature] = message.split('--', 2)
hmac = crypto.createHmac(algorithm, secret)
digest = hmac.digest('hex')
if digest == signature
return MessageVerifier.deserializer((new Buffer(data, 'base64')).toString('utf8'))
throw new Error("Invalid signature!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment