使用HMAC SHA512 - Swift从API获取数据

时间:2016-09-03 08:12:09

标签: swift hmac sha512

我正在尝试使用描述here的API。它使用基于密钥的HMAC SHA512授权。

PHP中有一个实现示例:

function bitmarket_api($method, $params = array())
{
  $key = "klucz_jawny";
  $secret = "klucz_tajny";

  $params["method"] = $method;
  $params["tonce"] = time();

  $post = http_build_query($params, "", "&");
  $sign = hash_hmac("sha512", $post, $secret);
  $headers = array(
      "API-Key: " . $key,
      "API-Hash: " . $sign,
  );

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_URL, "https://www.bitmarket.pl/api2/");
  curl_setopt($curl, CURLOPT_POST, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  $ret = curl_exec($curl);

  return json_decode($ret);
}

然后我试图在Swift中实现它:

import Alamofire
import CryptoSwift

func getRawJSON(method: String, params: [String]) -> String {
    let publicKey = "publicKeyHere"
    let secretKey = "secretKeyHere"
    let APIURL = "https://www.bitmarket.pl/api2/"

    var params = [
        "method": method,
        "tonce:": NSDate().timeIntervalSince1970
        ] as [String : Any]

    let hmac: Array<UInt8> = try! HMAC(key: secretKey.utf8.map({$0}), variant: .sha512).authenticate(params)

    var headers = [
        "API-Key": publicKey,
        "API-Hash": hmac
    ] as [String : Any]
}

正如您可能已经注意到的那样,Alamofire还没有用于获取数据,因为我在准备发送数据时遇到了问题。我的意思是我用CryptoSwift弄乱了一些东西,因为当我试图声明Cannot convert value of type '[String : Any]' to expected argument type 'Array<UInt8>'变量时,我收到了这个错误:hmac

如何解决? 我可能不得不以某种方式将params数组转换为Array<UInt8,但我不知道该怎么做。我不确定一切都是正确的。

修改 感谢Martin R,实际代码是:

func getRawJSON(method: String, paramether: String) {
    let publicKey = "publicKeyHere"
    let secretKey = "secretKeyHere"
    let APIURL = "https://www.bitmarket.pl/api2/"

    let query = NSURLComponents()
    query.queryItems = [NSURLQueryItem(name: "method", value: method) as URLQueryItem,
                        NSURLQueryItem(name: "tonce", value: String(Int(NSDate().timeIntervalSince1970))) as URLQueryItem]

    let requestString = query.query!
    let requestData = Array(requestString.utf8)

    let params = [
        "method": method,
        "tonce:": String(Int(NSDate().timeIntervalSince1970))
        ] as [String : Any]

    let hmac: Array<UInt8> = try! HMAC(key: secretKey.utf8.map({$0}), variant: .sha512).authenticate(requestData)

    let hmacData = Data(bytes: hmac)
    let hmacString = hmacData.base64EncodedString()

    let headers = [
        "API-Key": publicKey,
        "API-Hash": hmacString
    ] as [String : String]

    Alamofire.request(APIURL, withMethod: .post, parameters: params, encoding: .url, headers: headers)
        .responseJSON { response in
        print(response)
    }
}

不幸的是,在调用函数(getRawJSON(method: "info", paramether: ""))之后,我正在获取一个带有错误的JSON:

{
error = 502;
errorMsg = "Invalid message hash";
time = 1472910139;
}

我的哈希有什么问题?

1 个答案:

答案 0 :(得分:0)

你的Swift代码缺少什么

$post = http_build_query($params, "", "&");

在PHP版本中执行:从给定参数创建查询字符串。 你可以手动&#34;构建该字符串,或使用NSURLComponents

let comps = NSURLComponents()
comps.queryItems = [ NSURLQueryItem(name: "method",
                                    value: "YOUR_METHOD"),
                     NSURLQueryItem(name: "tonce",
                                    value: String(Int(NSDate().timeIntervalSince1970))) ]
let requestString = comps.query!
print(requestString) // method=YOUR_METHOD&tonce=1472893376

最后将此字符串转换为HMAC的[UInt8]数组 功能:

let requestData = Array(requestString.utf8)
print(requestData) // [109, 101, 116, ..., 54]