0

I want to create an SHA1 hmac hash of a string using a key in swift. In obj-c I used this and it worked great:

+(NSString *)sha1FromMessage:(NSString *)message{

    const char *cKey  = [API_KEY cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [message cStringUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"%s", cData);

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA1, 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:@"%02hhx", buffer[i]];
    }
    return HMAC;
}

However now I am having a hard time to translate this into swift. This is what I have so far:

static func sha1FromMessage(message: String){

        let cKey = RestUtils.apiKey.cStringUsingEncoding(NSASCIIStringEncoding)!
        let cData = message.cStringUsingEncoding(NSUTF8StringEncoding)!
        let cHMAC = [CUnsignedChar](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)

        CCHmac(kCCHmacAlgSHA1, cKey, cKey.count, cData, cData.count, cHMAC)
        ...
}

and this line

CCHmac(kCCHmacAlgSHA1, cKey, cKey.count, cData, cData.count, cHMAC)

already gives me an error Int is not convertible to CCHmacAlgorithm. Any ideas how to translate the obj-c code to swift?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

2 Answers2

1

The last parameter of the CCHmac() function has the type UnsafeMutablePointer<Void> because that's where the result is written to. You have to declare cHMAC as variable and pass it as an in-out expression with &. In addition, some type conversions are necessary:

var cHMAC = [CUnsignedChar](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey, UInt(cKey.count), cData, UInt(cData.count), &cHMAC)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • +1 thank you! Can you help me translate the rest of the function? – DarkLeafyGreen Oct 31 '14 at 07:11
  • @artworkadシ: It seems that only the hex string generation is missing, and that is shown in http://stackoverflow.com/a/25762128/1187415, to which I pointed you already in an answer to your previous question. – Martin R Oct 31 '14 at 07:41
0

Apple enum values are defined differently in Swift. Instead of kCCHmacAlgSHA1, it's probably defined like CCHmacAlgorithm.SHA1.

This is answered here: https://stackoverflow.com/a/24411522/2708650

Community
  • 1
  • 1
Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51