Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Created May 12, 2015 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaSullivan/8182bf7e7e307203160d to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/8182bf7e7e307203160d to your computer and use it in GitHub Desktop.
Challenge Accepted #2 - Signed API Request
let inputDictionary = [
"author_name": "Robert Jordan",
"book_title": "Knife of Dreams",
"series": "The Wheel of Time, Book 11",
"publisher": "Tor Fantasy",
"published_date": "November 28, 2006"
]
let sortedKeys = inputDictionary.keys.array.sorted(<)
var queryTerms = Array<String>()
for key in sortedKeys {
let encodedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let encodedValue = inputDictionary[key]!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
queryTerms += ["\(encodedKey)=\(encodedValue)"]
}
let now = NSDate()
queryTerms += ["timestamp=\(Int(now.timeIntervalSince1970 * 1000.0))"]
let hashInputString = "&".join(queryTerms) + "1234MySuperSecretKey4321"
// NOTE: This next line makes use of the CryptoSwift library (https://github.com/krzyzanowskim/CryptoSwift/)
if let hash = hashInputString.sha1() {
queryTerms += ["signature=\(hash)"]
let finalQueryString = "&".join(queryTerms)
println(finalQueryString)
} else {
println("ERROR: Unable to create SHA-1 hash.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment