Sunday, 15 July 2012

ios - Create hash in swift using key and message -



ios - Create hash in swift using key and message -

i want create sha1 hmac hash of string using key in swift. in obj-c used , worked great:

+(nsstring *)sha1frommessage:(nsstring *)message{ const char *ckey = [api_key cstringusingencoding:nsasciistringencoding]; const char *cdata = [message cstringusingencoding:nsutf8stringencoding]; nslog(@"%s", cdata); unsigned char chmac[cc_sha1_digest_length]; cchmac(kcchmacalgsha1, ckey, strlen(ckey), cdata, strlen(cdata), chmac); nsdata *hmacdata = [nsdata datawithbytes:chmac length:sizeof(chmac)]; const unsigned char *buffer = (const unsigned char *)[hmacdata bytes]; nsmutablestring *hmac = [nsmutablestring stringwithcapacity:hmacdata.length * 2]; (int = 0; < hmacdata.length; ++i){ [hmac appendformat:@"%02hhx", buffer[i]]; } homecoming hmac; }

however having hard time translate swift. have far:

static func sha1frommessage(message: string){ allow ckey = restutils.apikey.cstringusingencoding(nsasciistringencoding)! allow cdata = message.cstringusingencoding(nsutf8stringencoding)! allow chmac = [cunsignedchar](count: int(cc_sha1_digest_length), repeatedvalue: 0) cchmac(kcchmacalgsha1, ckey, ckey.count, cdata, cdata.count, chmac) ... }

and line

cchmac(kcchmacalgsha1, ckey, ckey.count, cdata, cdata.count, chmac)

already gives me error int not convertible cchmacalgorithm. ideas how translate obj-c code swift?

the lastly parameter of cchmac() function has type unsafemutablepointer<void> because that's result written to. have declare chmac variable , pass in-out expression &. in addition, type conversions necessary:

var chmac = [cunsignedchar](count: int(cc_sha1_digest_length), repeatedvalue: 0) cchmac(cchmacalgorithm(kcchmacalgsha1), ckey, uint(ckey.count), cdata, uint(cdata.count), &chmac)

ios objective-c swift

No comments:

Post a Comment