如何在iOS Objective C中模拟CCHmacContext()?

时间:2017-05-13 05:00:43

标签: ios objective-c swift sha256 cchmac

我想将创建 Swift3 的方法转换为 Objective C

func HMAC_CREATOR(MIX_STR mixStr:String,KEY_DATA_UINT8 keyDataUint8:Array<UInt8>) -> String {
        let signatureData : Data = mixStr.data(using: .utf8)!
        let digest = UnsafeMutablePointer<UInt8>.allocate(capacity:Int(CC_SHA256_DIGEST_LENGTH))
        var hmacContext = CCHmacContext()
        CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), (keyDataUint8), (keyDataUint8.count))
        CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)
        CCHmacFinal(&hmacContext, digest)
        let macData = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))
        return  macData.hexEncodedString()
    }

1 个答案:

答案 0 :(得分:1)

将代码直接翻译成Objective-C是:

#include <CommonCrypto/CommonCrypto.h>

NSString *HMAC_CREATOR(NSString *mixStr, UInt8 *keyData, size_t keyDataLength) {
    NSData *signatureData = [mixStr dataUsingEncoding: NSUTF8StringEncoding];

    CCHmacContext hmacContext;
    CCHmacInit(&hmacContext, kCCHmacAlgSHA256, keyData, keyDataLength);
    CCHmacUpdate(&hmacContext, signatureData.bytes, signatureData.length);

    NSMutableData *digest = [[NSMutableData alloc] initWithCapacity: CC_SHA256_DIGEST_LENGTH];
    CCHmacFinal(&hmacContext, digest.mutableBytes);

    // hexEncodedString is not a member of NSData so I'm not sure what this is supposed to be.
    // Probably added in Swift by an extension
    return [digest hexEncodedString];
}

最后,棘手的部分就在那里。很明显,Swift代码包含一个函数(可能在扩展中),它将一个名为hexEncodedString的方法添加到NSData