Create a gist now

Instantly share code, notes, and snippets.

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)
hmac.update(base64)
"#{base64}--#{hmac.digest('hex')}"
verify: (message, secret, algorithm) ->
algorithm ?= 'sha1'
[data, signature] = message.split('--', 2)
hmac = crypto.createHmac(algorithm, secret)
hmac.update(data)
digest = hmac.digest('hex')
if digest == signature
return MessageVerifier.deserializer((new Buffer(data, 'base64')).toString('utf8'))
else
throw new Error("Invalid signature!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment