需要在 Objective C 中生成 HMAC SHA256 哈希值,就像在 Java 中一样
2022-09-03 09:27:43
我需要使用HMAC SHA256生成哈希值。我在Java中使用以下代码。我需要Objective-C中的等效代码。
javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
mac.init(secret);
byte[] digest = mac.doFinal(value.getBytes());
StringBuilder sb = new StringBuilder(digest.length * 2);
String s="";
for (byte b: digest) {
s = Integer.toHexString(b);
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
}
return sb.toString();
键 =YARJSuwP5Oo6/r47LczzWjUx/T8ioAJpUK2YfdI/ZshlTUP8q4ujEVjC0seEUAAtS6YEE1Veghz+IDbNQb+2KQ==
值 =
id=456|time=19:10|nonce=8
输出 =
4effffffd8ffffffce7cffffffc4ffffffc71b2f72ffffffdc21ffffffa1ffffffe0ffffffe62d32550b0771296bffffff9c1159ffffffdeffffff8675ffffff9928654c
我有这个Objective-C函数:
//Hash method Definition
- (NSString *)getHashEncription:(NSString *)key andData:(NSString *)data{
NSLog(@"Secret Key %@ And Data %@", key, data);
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
//HmacSHA256
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC
length:sizeof(cHMAC)];
[Base64 initialize];
NSString *b64EncStr = [Base64 encode:HMAC];
NSLog(@"Base 64 encoded = %@",b64EncStr);
NSLog(@"NSData Value %@", HMAC);
// unsigned char hashedChars[32];
// NSString *inputString;
// inputString = [NSString stringWithFormat:@"hello"];
// NSData * inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
// CC_SHA256(inputData.bytes, inputData.length, hashedChars);
return [[NSString alloc] initWithData:HMAC encoding:NSASCIIStringEncoding];
}//End of getHashEncription
我得到的输出是这样的:
8736bc4aa7fc3aa071f2b4262b6972a89d2861559a20afa765e46ff17cb181a9
我尝试删除base64编码,但它不起作用。
任何建议都非常欢迎。