SHA1 in base64 and HMAC in HEX output issues ios iphone -
iam having fun time implementing sha1 , hmac methods in iphone applecation. need access webservice(which not controll) , require both sha1 , hmac encryption.
for sha1 in base64 use following approach.
-(nsstring*)sha1ith64base:(nsstring *)stringtoencode { unsigned char result[cc_sha1_digest_length]; const char *cstr = [stringtoencode utf8string]; cc_sha1(cstr, strlen(cstr), result); nsdata *pwhashdata = [[nsdata alloc] initwithbytes:result length: sizeof result]; nsstring *base64 = [base64 encode:pwhashdata]; nslog(@"sha1 in base64 %@",base64); return base64; }
for hmac using following approach:
- (nsstring *) encodewithhmacsha1:(nsstring *)k0:(nsstring*)m0 { const char *ckey = [k0 cstringusingencoding:nsasciistringencoding]; const char *cdata = [m0 cstringusingencoding:nsasciistringencoding]; unsigned char chmac[cc_sha1_digest_length]; cchmac(kcchmacalgsha1, ckey, strlen(ckey), cdata, strlen(cdata), chmac); nsstring *s = [nsstring stringwithformat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", chmac[0], chmac[1], chmac[2], chmac[3], chmac[4], chmac[5], chmac[6], chmac[7], chmac[8], chmac[9], chmac[10], chmac[11], chmac[12], chmac[13], chmac[14], chmac[15], chmac[16], chmac[17], chmac[18], chmac[19] ]; nslog(@"hmac in hex %@",s); return s; }
but question there way can test these methods locally , not gainst webservice - can rule out errors wbservice.
regards
solved: testing implementations use following method - hopes can someone, 1 day.
-(void)testencryptions { nsstring *key = @"jefe"; nsstring *data = @"what ya want nothing?"; nsstring *digestanswerhmac =@"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"; nsstring *digestanswersha1hex =@"cb5551f403fac5fd3d6d1b6329993c3848c468ce"; nsstring *disgest64base=@"smvmzq=="; nsdata *stringbytes = [key datausingencoding: nsutf8stringencoding]; nsstring *hash = [base64 encode:stringbytes]; ////// nslog(@"testing encryptions"); nslog(@"testing hmac encryptions :%@ should :%@",[self encodewithhmacsha1:key :data],digestanswerhmac); nslog(@"testing sha1 in hex encryption :%@ should :%@",[self sha1:key],digestanswersha1hex); nslog(@"testing base64 :%@ should :%@",hash,disgest64base); nslog(@"testing sha1 in 64 1234 %@ , should crdtpncebiql5koqskvyra0saia=",[self sha1ith64base:@"1234"]); }
in order test key hashing methods need establish known set of test data. way know expected output based on matching input. can lot of different standard test data rfc2202
testing implementations therefore handled few unit tests compares these well-known data sets.
if want test encoding query webservice , handling response correctly kind of stub or mock testing. again need establish known set of input data , expected output.
once have reference test set can implement custom nsurlprotocol act real webservice instead provide "reference" response. have detailed description of topic on blog:
Comments
Post a Comment