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

Converting SHA1 string encryption code from objective-c to swift

所以这是我原来的 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 项目中。请协助。

试试这个:

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)
}

我个人的经验是Swift非常讨厌指针。如果您的代码大量使用指针,将它们写在 C/ObjC.

中会更容易