0
我試圖執行從斯威夫特3的HMAC-SHA1簽名到inreturn重定向到Twitter的主機香港服務器(要在香港實現HMAC - 其次https://getkong.org/plugins/hmac-authentication/)HMAC-SHA1斯威夫特3 - 403禁止
我在我的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簽名紫禁城無法驗證