Signature example in Scala

package signalvine

import javax.crypto.spec.SecretKeySpec
import javax.crypto.Mac
import play.api.libs.json._

object SignatureService {
  def buildString(token: String, httpVerb: String, path:String, timestamp: DateTime, body: JsValue): Either[String, String] = {
    val fmt = ISODateTimeFormat.dateTime()
    val isoStr = fmt.print(timestamp)
    val bodyStr = Json.stringify(body)

    val normalizedFields =
      Seq(token.toLowerCase(), httpVerb.toLowerCase(), path.toLowerCase(), body.toLowerCase(), isoStr.toLowerCase())

    normalizedFields.count(_.isEmpty) match {
      case 0 => Right(normalizedFields.mkString("\n"))
      case _ => Left("Required fields missing")
    }
  }

  def sign(clientId: String, secret: String, method: String, path: String, timeStamp: String, body: String = ""): String = {
    val stringToSign = buildString(clientId, method, path, timeStamp, body)
    val sec = secret.getBytes(StandardCharsets.UTF_8)

    val key = new SecretKeySpec(sec, "HmacSHA256")
    val value = stringToSign.getBytes("utf-8")

    val mac = Mac.getInstance("HmacSHA256")
    val signature = mac.init(sec).doFinal(value)

    val encoder = new sun.misc.BASE64Encoder()

    encoder.encode(data)
  }
}
Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments

0 comments

Please sign in to leave a comment.