这是一个如何形成NSURLRequest
for的示例poloniex.com
。
想象一下你的:
API Key
= @"apikey"
Secret
= @“秘密”
nonce
= @“1”
从最简单的事情开始:
NSMutableURLRequest *theURLRequest = [NSMutableURLRequest new];
theURLRequest.URL = [NSURL URLWithString:@"https://poloniex.com/tradingApi"];
theURLRequest.HTTPMethod = @"POST";
NSString *theBodyString = @"command=returnBalances&nonce=1";
theURLRequest.HTTPBody = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[theURLRequest setValue:@"apikey" forHTTPHeaderField:@"Key"];
现在最难的一点...
对我而言,Poloniex 文档并不太清楚他们想要在"Sign"
标头字段值下什么,但基本上他们希望您传递一个字符串,这应该是HMAC SHA512
应用于两者的加密算法theBodyString
的 Secret
结果(在我们的示例中只是@“秘密”)。
这是返回给你的函数HMAC SHA512
NSData
:
#import <CommonCrypto/CommonHMAC.h>
NSData * getHMACSHA512FromSecretKeyStringAndBodyString(NSString *theSecretKeyString, NSString *theBodyString)
{
const char *cSecret = [theSecretKeyString cStringUsingEncoding:NSUTF8StringEncoding];
const char *cBody = [theBodyString cStringUsingEncoding:NSUTF8StringEncoding];
unsigned char cHMAC[CC_SHA512_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA512, cSecret, strlen(cSecret), cBody, strlen(cBody), cHMAC);
return [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
}
所以,运行:
NSData *theData = getHMACSHA512FromSecretKeyStringAndBodyString(@"secret", @"command=returnBalances&nonce=1");
NSString *theString = [NSString stringWithFormat:@"%@", theData];
会给我们几乎我们想要的东西。
我们的结果等于:
<c288f881 a6808d0e 78827ec6 ca9d6b9c 34ec1667 07716303 0d6d7abb 2b225456 31176f52 8347ab0f d6671ec5 3aec1f7d 3b6de8b8 e3ccc23d e62fd594 52d70db5>
虽然我们真正想要的(根据http://www.freeformatter.com/hmac-generator.html)是:
c288f881a6808d0e78827ec6ca9d6b9c34ec1667077163030d6d7abb2b22545631176f528347ab0fd6671ec53aec1f7d3b6de8b8e3ccc23de62fd59452d70db5
因此,基本上,只需从字符串中删除<
,>
和
符号;
theString = [theString stringByReplacingOccurrencesOfString:@"<" withString:@""];
theString = [theString stringByReplacingOccurrencesOfString:@">" withString:@""];
theString = [theString stringByReplacingOccurrencesOfString:@" " withString:@""];
[theURLRequest setValue:theString forHTTPHeaderField:@"Sign"];
你theURLRequest
现在已经准备好了,应该可以成功获得tradingApi
of poloniex.com
。