【问题标题】:HMAC Base64 Authentication?HMAC Base64 身份验证?
【发布时间】:2018-05-28 03:09:11
【问题描述】:

我不知道其中发生了什么,但我正在尝试使用 API,他们还有另一个不同的身份验证标准,称为 HMAC,带有 Sha384 到 base64。

这是提供的示例:

class ICObenchAPI {

private $privateKey = 'private-key';
private $publicKey  = 'public-key';
private $apiUrl     = 'https://icobench.com/api/v1/';
public  $result;

public function getICOs($type = 'all', $data = ''){ 
    return $this->send('icos/' . $type, $data); 
}   
public function getICO($icoId, $data = ''){ 
    return $this->send('ico/' . $icoId, $data); 
}       
public function getOther($type){ 
    return $this->send('other/' . $type, ''); 
}

private function send($action, $data){

    $dataJson = json_encode($data);                 
    $sig = base64_encode(hash_hmac('sha384', $dataJson, $this->privateKey, true));  

    $ch = curl_init($this->apiUrl . $action);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($dataJson),
        'X-ICObench-Key: ' . $this->publicKey,
        'X-ICObench-Sig: ' . $sig)
    );

    $reply = curl_exec($ch);
    $ff = $reply;
    $reply = json_decode($reply,true);

    if(isset($reply['error'])){
        $this->result = $reply['error'];
        return false;
    }else if(isset($reply['message'])){
        $this->result = $reply['message'];
        return true;
    }else if(isset($reply)){
        $this->result = json_encode($reply);
        return true;
    }else{
        $this->result = htmlspecialchars($ff);
        return false;
    }
}

public function result(){
    return $this->result;
}

}

我正在寻找提供的 PHP 示例并将其转换为 nodeJS 脚本,只是真的不知道从哪里开始。我看过crypto-js和其他人,但只是不理解我什至在写的请求中具体发生了什么

【问题讨论】:

    标签: php node.js base64 sha hmac


    【解决方案1】:

    Crypto-js 是个好方法。

    您需要先加密您的数据,然后再对其进行 Base64 加密,以创建在标头中使用的签名

        let dataJSON = JSON.stringify(data);
    
        let sign = CryptoJS.HmacSHA384(dataJSON, this.privateKey);
        sign = CryptoJS.enc.Base64.stringify(sign);
    

    我在 github 上推送了一个工作示例:ICObenchAPI.js

    【讨论】:

      【解决方案2】:

      我编写了一个名为 node-icobench 的 Node js 包装库。欢迎您使用。

      npm install node-icobench

      为了这个例子,下面是对 HMAC 部分的一些改动:

      const crypto = require('crypto');
      
      // Stringify POST data
      let jsonData = JSON.stringify(data);
      
      // Create HMAC based on algo and private key
      let hmac = crypto.createHmac('sha384', privateKey);
      
      // Create HMAC Digest of json data
      hmac.update(jsonData);
      
      // return Base64 encoding of HMAC
      let signedData = hmac.digest('base64');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        • 1970-01-01
        • 2013-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多