Created
October 29, 2011 04:03
-
-
Save cldellow/1324052 to your computer and use it in GitHub Desktop.
Ravelry crypto
This file contains hidden or 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
| object Crypto { | |
| /** Sign a request as a user */ | |
| def sign(url: String, params: Map[String, String], token: String, secret: String): String = { | |
| val paramsToSign = params ++ commonParams ++ Map("auth_token" -> token) | |
| finalsign(url, paramsToSign, secret) | |
| } | |
| /** Sign a request as Ballero */ | |
| def appsign(url: String, params: Map[String, String]): String = { | |
| val paramsToSign = params ++ commonParams | |
| finalsign(url, paramsToSign, Keys.secret) | |
| } | |
| private def finalsign(url: String, params: Map[String, String], secret: String): String = { | |
| val proveMe = "%s?%s".format(url, params.keySet.toList.sorted | |
| .map { name => (name, params(name)) } | |
| .map { case (name, value) => "%s=%s".format(encode(name), encode(value)) }.mkString("&") | |
| ) | |
| val hmac256 = new HmacSha256 | |
| val signature = Base64.encode(hmac256.create(secret, proveMe)) | |
| "%s&signature=%s".format(proveMe, encode(signature)) | |
| } | |
| private def commonParams: Map[String, String] = | |
| Map("access_key" -> Keys.key, "timestamp" -> iso8601) | |
| /** Gets an ISO8601 formatted timestamp. */ | |
| private def iso8601: String = { | |
| val now = new Date() | |
| val sdf: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000Z") | |
| sdf.format( now ) | |
| } | |
| private def encode(str: String): String = java.net.URLEncoder.encode(str, "UTF-8") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment