Skip to content

Instantly share code, notes, and snippets.

@jmcardon
Last active December 12, 2017 09:21
Show Gist options
  • Select an option

  • Save jmcardon/5e2665e5eadf0d34435c948e2dd73fc7 to your computer and use it in GitHub Desktop.

Select an option

Save jmcardon/5e2665e5eadf0d34435c948e2dd73fc7 to your computer and use it in GitHub Desktop.
package io.github.jmcardon.tseclogin
import tsec.common._
import tsec.mac.core.MAC
import tsec.mac.imports._
import java.util.UUID
import java.time._
import cats.effect.IO
//Using cats-effect 0.5.0 and tsec 0.0.1-M6
object HmacExample {
case class Order(
orderNumber: UUID,
email: String,
timestamp: Instant,
nonce: SecureRandomId,
hash: MAC[HMACSHA256]
)
def authenticateOrderParams(
ord: UUID,
email: String,
time: Instant,
nonce: SecureRandomId,
key: MacSigningKey[HMACSHA256]
): IO[MAC[HMACSHA256]] =
for {
concat <- IO.pure((ord.toString + email + time.toString + nonce).utf8Bytes)
hashed <- JCAMac.sign[IO, HMACSHA256](concat, key)
} yield hashed
def generateOrder(key: MacSigningKey[HMACSHA256]): IO[Order] =
for {
ord <- IO(UUID.randomUUID())
email <- IO.pure("hi@hi")
time <- IO(Instant.now())
id <- IO(SecureRandomId.generate)
mac <- authenticateOrderParams(ord, email, time, id, key)
} yield Order(ord, email, time, id, mac)
def checkOrder(
order: Order,
ord: UUID,
email: String,
time: Instant,
nonce: SecureRandomId,
key: MacSigningKey[HMACSHA256]
): IO[Boolean] =
for {
concat <- IO.pure((ord.toString + email + time.toString + nonce).utf8Bytes)
verified <- JCAMac.verify[IO, HMACSHA256](concat, order.hash, key)
} yield verified
def main(args: Array[String]): Unit = {
val sillyProgram: IO[Unit] = for {
key <- HMACSHA256.generateLift[IO] //get a key
order <- generateOrder(key)
verified <- checkOrder(order, order.orderNumber, order.email, order.timestamp, order.nonce, key)
} yield println(s"Order number ${order.orderNumber} has been verified as $verified!!")
sillyProgram.unsafeRunSync()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment