Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add Crypto.sign functions

  • Loading branch information...
commit 776e882eec1de4c04eff196776e78820ddf756a5 1 parent 7b39ccd
@sgodbillon sgodbillon authored
View
21 framework/play/src/main/scala/play/api/libs/Codec.scala
@@ -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))
+ }
}
View
24 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")
+ }
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.