Skip to content

Commit

Permalink
add Crypto.sign functions
Browse files Browse the repository at this point in the history
  • Loading branch information
sgodbillon committed Oct 26, 2011
1 parent 7b39ccd commit 776e882
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
21 changes: 21 additions & 0 deletions framework/play/src/main/scala/play/api/libs/Codec.scala
Expand Up @@ -27,4 +27,25 @@ object Codec {
*/
def sha1(text: String): String = sha1(text.getBytes)

private val hexChars = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')

/**
* Converts a byte array into an array of char denoting a hexadecimal representation
*/
def toHex(array: Array[Byte]): Array[Char] = {
val result = new Array[Char](array.length * 2)
for (i <- 0 until array.length) {
val b = array(i) & 0xff
result(2 * i) = hexChars(b >> 4)
result(2 * i + 1) = hexChars(b & 0xf)
}
result
}

/**
* Converts a byte array into a String denoting a hexadecimal representation
*/
def toHexString(array: Array[Byte]): String = {
new String(toHex(array))
}
}
24 changes: 24 additions & 0 deletions framework/play/src/main/scala/play/api/libs/Crypto.scala
@@ -0,0 +1,24 @@
package play.api.libs

import java.security._
import javax.crypto._
import javax.crypto.spec.SecretKeySpec

import play.api.Play
import play.api.PlayException
import play.api.Configuration.Config

object Crypto {
def sign(message: String, key: Array[Byte]): String = {
val mac = Mac.getInstance("HmacSHA1")
mac.init(new SecretKeySpec(key, "HmacSHA1"))
Codec.toHexString(mac.doFinal(message.getBytes("utf-8")))
}

def sign(message: String): String = {
Play.maybeApplication.get.configuration.get("application.secret") match {
case Some(Config(key, value, file)) => sign(message, value.getBytes)
case _ => throw PlayException("Configuration error", "Missing application.secret")
}
}
}

0 comments on commit 776e882

Please sign in to comment.