IOS HMAC-SHA1 is different from the standard Java HMAC-SHA1

I need cHMAC with SHA512 encryption. I got the use of an encrypted value. This method and server-side value do not match the server side on which they use Java. Can plz help me understand this problem.

serveride encrted value

85d86c928825ef85d5329893f2cf2cba9ba6354582d54b5f1c7aaf69b6d72f71b742ae67f3e400d2e4b367f62a45b9948b512ae9a8efc0bcd667f1cdb0a66c6d 

objective-c encrypted value

  f242340a3664ea149717b943087cb8a5d92d6d25af5f5d8e0f51a6c4f0c1060830128e0798e6b300a81a1401612f0000d75d0000d3e27401e8d9ffbf221e1401 

Objetive-C Code:

 -(NSString *)createSHA512:(NSString *)string withKey:(NSString *)key { NSLog(@"key isss %@",key); NSLog(@"string isss %@",string); const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; const char *cData = [string cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cHMAC[CC_SHA512_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); NSData *HMACData = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; const unsigned char *buffer = (const unsigned char *)[HMACData bytes]; NSLog(@"bytes data is %@",HMACData); NSString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2]; for (int i = 0; i < HMACData.length; ++i) HMAC = [HMAC stringByAppendingFormat:@"%02lx", (unsigned long)buffer[i]]; return HMAC; } 

Java Code:

 public static String SHA512(String ta, String key, String xtra){ Digest digest = new SHA512Digest (); HMac hmac = new HMac(digest); String temp =ta.concat(key.concat(xtra)); hmac.init(new KeyParameter(key.getBytes())); hmac.update(temp.getBytes(), 0, temp.length()); byte[] resBuf = new byte[digest.getDigestSize()]; hmac.doFinal(resBuf, 0); String resStr = convertToHex(resBuf); return resStr; } 

Where did I make a mistake? if anyone knows about this, please share me to solve this problem.

+4
source share
1 answer

I cannot find the documentation for the HMac class that you are using, but I strongly suspect that you are using the doFinal method doFinal . I suspect you want:

 byte[] results = hmac.doFinal(temp.getBytes(), 0, temp.length()); 

... although you really shouldn't use getBytes() like this, with the default encoding of the platform. It would be better to write:

 byte[] binaryData = temp.getBytes("UTF-8"); byte[] results = hmac.doFinal(binaryData); 

EDIT: As noted in the comments, you are using ASCII in Objective-C code. You must select an encoding and use it in both places - I would recommend UTF-8.

+3
source

Source: https://habr.com/ru/post/1497064/


All Articles