我需要帮助,使用HMAC
SHA1
在swift 3中为网络请求制作签名。
我在Java中有一个例子,但实际上不知道如何在swift中完成它。
Java公式:
signature = Base64.encode(HMAC_SHA1.digest(data,Base64.decode(client_secret))
signature = +t2GOKtZt1hU+C7OGBKZbDOKxds=
答案 0 :(得分:0)
解决方案:
extension Data {
func hmacsha1(key: String) -> String? {
guard let keyData = Data(base64Encoded: key, options: .ignoreUnknownCharacters) else {
return nil
}
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
self.withUnsafeBytes({ dataBytes in
keyData.withUnsafeBytes({ keyDataBytes in
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), keyDataBytes, keyData.count, dataBytes, self.count, &digest)
})
})
return Data(bytes: digest).base64EncodedString()
}
}
测试:
let data = Data("Test".utf8)
let key = Data("Key".utf8).base64EncodedString()
let hmac = data.hmacsha1(key: key)
结果:"xIcCRlnXa+IqFtO+9AF3OqeRdAU="
答案 1 :(得分:0)
imgData = UIImageJPEGRepresentation(image, 0.9)! as Data
strBase64 = imgData.base64EncodedString(options: .lineLength64Characters) as NSString
然后在任何地方使用此base64字符串。
答案 2 :(得分:0)
问题解决了
EditText