将SHA1字符串加密代码从objective-c转换为swift

时间:2016-12-20 22:23:42

标签: objective-c swift cryptography sha1

所以这是我原来的Objective-C代码:

- (NSString *)calculateSignaturewithAPIKey:(NSString *)apiKey apiKeyPrivate:(NSString *)apiKeyPrivate httpMethod:(NSString *)httpMethod route:(NSString *)theRoute andExpiresIn:(NSString *)expireTime {
    NSString *string_to_sign = [NSString stringWithFormat:@"%@:%@:%@:%@",apiKey,httpMethod,theRoute,expireTime];

    const char *cKey  = [apiKeyPrivate cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [string_to_sign cStringUsingEncoding:NSASCIIStringEncoding];

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

    NSString *signature = [HMAC base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return signature;
}

在Swift 3中,我设法达到:

func calculateSignature(withPublicApiKey publicApiKey: String, andApiPrivateKey privateApiKey: String, withHttpMethod httpMethod: String, andRoute route: String, exiresIn expireTime: String) -> String {
    let string_to_sign = "\(publicApiKey):\(httpMethod):\(route):\(expireTime)"

    let cKey = privateApiKey.cString(using: String.Encoding.ascii)
    let cData = Data.base64EncodedString(Data.init)

    var cHMAC = [CUnsignedChar](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))

但我不知道该怎么办。我已经能够将加密相关的东西导入到我的Swift项目中。请协助。

1 个答案:

答案 0 :(得分:0)

试试这个:

func calculateSignature(withPublicApiKey publicApiKey: String, andApiPrivateKey privateApiKey: String, withHttpMethod httpMethod: String, andRoute route: String, exiresIn expireTime: String) -> String {
    let string_to_sign = "\(publicApiKey):\(httpMethod):\(route):\(expireTime)"
    let cKey = privateApiKey.cString(using: .ascii)!
    let cData = string_to_sign.cString(using: .ascii)!

    var cHMAC = [CUnsignedChar](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
    CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey, cKey.count - 1, cData, cData.count - 1, &cHMAC)

    let HMAC = Data(bytes: &cHMAC, count: Int(CC_SHA1_DIGEST_LENGTH))
    return HMAC.base64EncodedString(options: .lineLength64Characters)
}

我个人的经验是,斯威夫特真的很讨厌指针。如果您的代码大量使用指针,那么在C / ObjC中编写代码就更容易了。