Created
May 12, 2015 15:57
-
-
Save JoshuaSullivan/8182bf7e7e307203160d to your computer and use it in GitHub Desktop.
Challenge Accepted #2 - Signed API Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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