我需要使用SHA512加密的cHMAC我使用加密值这个方法和服务器端值不匹配服务器端他们使用Java可以帮助我解决这个问题。
服务器端被绑定的值是
85d86c928825ef85d5329893f2cf2cba9ba6354582d54b5f1c7aaf69b6d72f71b742ae67f3e400d2e4b367f62a45b9948b512ae9a8efc0bcd667f1cdb0a66c6d
objective-c加密值是
f242340a3664ea149717b943087cb8a5d92d6d25af5f5d8e0f51a6c4f0c1060830128e0798e6b300a81a1401612f0000d75d0000d3e27401e8d9ffbf221e1401
Objetive-C代码:
-(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代码:
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;
}
我在哪里弄错了?如果有人知道这个可以请你分享我来解决这个问题
答案 0 :(得分:3)
我找不到您正在使用的HMac
课程的文档,但我强烈怀疑您错误地使用了doFinal
方法。我怀疑你想要:
byte[] results = hmac.doFinal(temp.getBytes(), 0, temp.length());
...虽然你真的,但不应该使用getBytes()
这样的平台默认编码。最好写一下:
byte[] binaryData = temp.getBytes("UTF-8");
byte[] results = hmac.doFinal(binaryData);
编辑:如评论中所述,您在Objective-C代码中使用ASCII。您应该选择一个编码并在两个地方使用它 - 我建议使用UTF-8。