【发布时间】:2017-01-11 07:10:38
【问题描述】:
我正在尝试使用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;
}
我的哈希有什么问题?
【问题讨论】: