简体   繁体   中英

IOS HMAC-SHA1 Different than Standard Java HMAC-SHA1

I need cHMAC with SHA512 encryption I got using encrypted value this method and server side value is not matched server side they are using Java can plz help me to figure this issue.

serverside encrted value is

85d86c928825ef85d5329893f2cf2cba9ba6354582d54b5f1c7aaf69b6d72f71b742ae67f3e400d2e4b367f62a45b9948b512ae9a8efc0bcd667f1cdb0a66c6d

objective-c encrypted value is

  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 have I made a mistake? if anyone know regarding this can u please share me to solve this issue

I can't find documentation for the HMac class you're using, but I strongly suspect you're using the doFinal method incorrectly. I suspect you want:

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

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

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

EDIT: As noted in comments, you're using ASCII in the Objective-C code. You should pick an encoding and use it in both places - I'd recommend UTF-8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM