【问题标题】:Converting SHA1 string encryption code from objective-c to swift将SHA1字符串加密代码从objective-c转换为swift
【发布时间】:2016-12-20 22:23:41
【问题描述】:

所以这是我拥有的原始 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))

但我不知道如何继续。我已经能够将 Crypto 相关的东西导入到我的 Swift 项目中。请帮忙。

【问题讨论】:

标签: objective-c swift cryptography sha1


【解决方案1】:

试试这个:

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 编写它们会更容易。

【讨论】:

  • 试过这个,甚至尝试使用 GitHub 上的加密框架来实现这个。基本上会发生什么,如果你把公钥放到“1234”,把私钥放到“abcd”,路由到“forms/1/entries”httpmethod到“GET”,过期时间到“1369749344”它应该吐出这样的字符串uJEnk0EoQ4d3iinjFMBrBzZfH9w= 但是 swift 对你的方法做了什么,而不是试图在这里说任何坏话,因为我得到了完全相同的结果是这样的:“688fdb5f5ce51a298f91aa768391e14dcdbe3ca6”,你可以看到它们非常不同。对我自己来说,最后的办法是将objective-c桥接到我的项目中。
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多