【问题标题】:Node Hmac Authentication节点 Hmac 认证
【发布时间】:2017-02-14 23:21:00
【问题描述】:

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

Example client

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

问题

  • 上述过程描述正确吗?
  • 如何解密签名并将其与有效负载进行比较?
  • 或者我应该以与客户端相同的方式对其进行加密然后进行比较?
  • update&digestNode 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

【问题讨论】:

    标签: node.js hmac


    【解决方案1】:

    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"});
        });
      }
    

    【讨论】:

    • 客户的secret_key应该放在哪里?
    【解决方案2】:

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

    if(compute_hmac != hmac) {
    
    return authSignature == signature
    

    最好用:

    crypto.timingSafeEqual(a, b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-18
      • 2013-06-05
      • 2021-09-14
      • 1970-01-01
      • 2021-01-09
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多