我正在尝试从 Swift 3 到 kong 服务器执行 HMAC-SHA1 签名,该服务器返回重定向到 Twitter 主机(要在 Kong 上启用 HMAC - 遵循https://getkong.org/plugins/hmac-authentication/)
我在我的swift中使用相同的密钥,用户名。使用密钥在当前日期执行 HMAC-SHA1 并向http://localhost:8000/@foo发送请求
斯威夫特 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 签名无法验证的消息