0

I am trying to convert the following Java code to Objective-C. I have try some HMASHA256 function but the return signature at the end return different string.

JAVA

public static byte[] hmac256(byte[] key, String msg) throws Exception {
     Mac mac = Mac.getInstance("HmacSHA256");
     SecretKeySpec secretKeySpec = new SecretKeySpec(key,mac.getAlgorithm());
     mac.init(secretKeySpec);
     return mac.doFinal(msg.getBytes(UTF8));
}
byte[] secretDate = hmac256(("TC3" + SECRET_KEY).getBytes(UTF8), date);
byte[] secretService = hmac256(secretDate, service);
byte[] secretSigning = hmac256(secretService, "tc3_request");
String signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
System.out.println(signature);

Objective-C

- (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key
{
    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [plaintext cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
    
    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
    NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
    for (int i = 0; i < HMACData.length; ++i){
        [HMAC appendFormat:@"%02x", buffer[i]];
    }
    
    return HMAC;
}
NSString * date = [NSString stringWithFormat:@"TC3%@",SECRET_KEY];    
NSString * secretDate = [self hmac:dateString withKey:date];
NSString * secretService = [self hmac:service withKey:secretDate];
NSString * secretSigning = [self hmac:@"tc3_request" withKey:secretService];
NSString * signatureString = [self hmac:stringToSign withKey:secretSigning];

Community
  • 1
  • 1
  • Why `NSASCIIStringEncoding` and not `NSUTF8StringEncoding`? – trojanfoe Oct 09 '19 at 08:09
  • @trojanfoe I had tried NSASCIIStringEncoding and NSUTF8StringEncoding, it return the same string – M139ck23kdad Oct 09 '19 at 08:13
  • Very similar issue: [Same hashing algorithm in Java and Swift gives different result](https://stackoverflow.com/questions/57426401/same-hashing-algorithm-in-java-and-swift-gives-different-result) – Cristik Oct 09 '19 at 17:18

0 Answers0