public
Last active

MessageVerifier implementation for node.js

  • Download Gist
message_verifier.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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!")

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.