节点Hmac身份验证

时间:2016-10-06 09:18:51

标签: node.js hmac

我对身份验证过程的理解。主持人创建secretpublic api key。客户端在秘密的帮助下加密有效载荷,这是签名。然后将其公钥,有效负载,签名发送给主机。

Example client

主机检查是否允许公钥执行操作并根据客户端公钥获取密钥。在秘密的帮助下,主机解密签名并将其与有效载荷进行比较。

问题

  • 上述过程是否正确描述?
  • 如何解密签名并将其与有效负载进行比较?
  • 或者我应该以与客户端dos相同的方式加密它并比较它呢?
  • 这两个步骤update& digest Node Docs

客户端:

  authenticate: (self)->
    payload = 'AUTH' + moment()
    signature = crypto.createHmac('sha384', WEBSOCKET_SECRET)
      .update(payload)
      .digest('hex')

    data = {
      event: 'auth',
      apiKey: WEBSOCKET_KEY,
      authSig: signature,
      authPayload: payload
    }
    self.send self, data

服务器:

hmac = crypto.createHmac('sha384', WEBSOCKET_SECRET)
hmac.on 'readable', () ->
  data = hmac.read()
  if (data)
    console.log data, data.toString('utf-8')


# hmac.write(authPayload)
hmac.write(signature)
hmac.end()

当前服务器端解决方案

  authenticate: (authPublicKey, authSignature, authPayload)->
    signature = crypto.createHmac('sha384', WEBSOCKET_SECRET)
      .update(authPayload)
      .digest('hex')

    return authSignature == signature

2 个答案:

答案 0 :(得分:4)

HMAC不用于加密/解密,仅用于身份验证和数据完整性检查。

客户端用他的密钥发送他的有效载荷,他的PK和他的有效载荷的hmac。 服务器用他的pk检索用户,用检索到的sk重新计算hmac,然后检查计算的hmac是否等于检索到的hmac。

客户端有一个公钥和密钥:

var str        = payload_string;
var public_key = pk;
var secret_key = sk;

var hmac = crypto.createHmac('sha384', sk).update(str).digest('hex');

request.post({uri:..., json: { hmac, public_key, payload: str }, function(err, response, body) {
   console.log(body);
});

在服务器上:

exports.... = function(req, res)
{
   var hmac = req.body.hmac;
   var pk = req.body.public_key;
   var payload  = req.body.payload;


   // retrieve authorized user
   User.findOne({ pk }, function(err, user) {
      if(err || !user){
        return res.status(403).json({error:"Invalid user"});
      }

      // recompute hmac
      var compute_hmac= crypto.createHmac('sha384', user.sk).update(payload).digest('hex');

      // check hmac
      if(compute_hmac != hmac) {
        return res.status(403).json({error:"Security check failed"});
      }
      // do stg
      return res.status(200).json({success:"ok"});
    });
  }

答案 1 :(得分:2)

这些行容易受到定时攻击:

if(compute_hmac != hmac) {

return authSignature == signature

最好使用:

crypto.timingSafeEqual(a, b)