gpt4 book ai didi

ios - HMAC-SHA1 Swift 3 - 403 禁止

转载 作者:行者123 更新时间:2023-11-30 12:19:46 31 4
gpt4 key购买 nike

我正在尝试从 Swift 3 到 kong 服务器执行 HMAC-SHA1 签名,该服务器反过来重定向到 Twitter 主机(要在 Kong 上启用 HMAC - 随后 https://getkong.org/plugins/hmac-authentication/ )

我在我的 swift 中使用相同的 key 、用户名。使用 key 在当前日期执行 HMAC-SHA1 并将请求发送到 http://localhost:8000/@foo

Swift 3 代码:

override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let currentDateF = DateFormatter()
let localeF = Locale(identifier: "en_US")
let tzone = TimeZone(identifier: "UTC")
currentDateF.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
currentDateF.timeZone = tzone
currentDateF.locale = localeF
let currentDate = currentDateF.string(from: date)
let dat = "date: \(currentDate)"
let username = "bar"
let hmacResult: String = dat.getHmac(algorithm: .SHA1, key: "foo")
HTTPrequest(Datestr: currentDate, hmacAuth: hmacResult, username: username)
}

func HTTPrequest(Datestr: String, hmacAuth: String, username: String) {
let url = URL(string: "http://localhost:8000/@foo")
var request = URLRequest(url: url!)
request.addValue(Datestr, forHTTPHeaderField: "date")
request.addValue("twitter.com", forHTTPHeaderField: "Host")
request.setValue("hmac username='\(username)', algorithm='hmac-sha1', headers='date', signature='\(hmacAuth)'", forHTTPHeaderField: "Authorization")
let dataTask = URLSession.shared.dataTask(with: request) {
(data,response,error) in
if error != nil {
print(error!)
}
print("DATA RETURNED: \(data!)")
let str = String(data: data!, encoding: .utf8)
print("VALUE: \(str!)")
print("RESPONSE: \(response!)")
}
dataTask.resume()
}


enum hmacAlgo {
case SHA1
func toHMACAlgorithm() -> CCHmacAlgorithm {
var result: Int = 0
switch self {
case .SHA1:
result = kCCHmacAlgSHA1
}
return CCHmacAlgorithm(result)
}

func digestLength() -> Int {
var result: CInt = 0
switch self {
case .SHA1:
result = CC_SHA1_DIGEST_LENGTH
}
return Int(result)
}
}

extension String {
func getHmac(algorithm: hmacAlgo, key: String) -> String {
let stringData = self.cString(using: String.Encoding.ascii)
let keyData = key.cString(using: String.Encoding.ascii)
var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength()))
CCHmac(algorithm.toHMACAlgorithm(), keyData!, Int(strlen(keyData!)), stringData!, Int(strlen(stringData!)), &result)
let hmacData: NSData = NSData(bytes: result, length: (Int(algorithm.digestLength())))
let hmacb64 = hmacData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
return hmacb64
}
}

但我收到 403 状态代码 - 禁止,并显示消息说明无法验证 HMAC 签名

最佳答案

解决了,

request.setValue("hmac username=\"\(username)\", algorithm=\"hmac-sha1\", headers=\"date\", signature=\"\(hmacAuth)\"", forHTTPHeaderField: "Authorization")

我只是用双引号将字符串括在授权 header 中并发送了请求。谢谢。

关于ios - HMAC-SHA1 Swift 3 - 403 禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941277/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com