Skip to content

Commit

Permalink
hmac.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed May 11, 2022
1 parent fa05683 commit 8dec37c
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
55 changes: 55 additions & 0 deletions src/main/scala/sha256/Hmac.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package sha256

import scala.scalanative.libc.stdlib
import scala.scalanative.libc.string
import scala.scalanative.unsafe._
import scala.scalanative.unsigned._

object Hmac {
def hmac(
key: Array[UByte],
msg: Array[UByte]
): Array[UByte] = {
Zone { implicit z =>
{
val keySize = key.size.toLong.toULong
val keyData = alloc[UByte](keySize).asInstanceOf[Ptr[UByte]]
for (i <- 0 until key.size) {
!(keyData + i) = key(i)
}

val msgSize = msg.size.toLong.toULong
val msgData = alloc[UByte](msgSize).asInstanceOf[Ptr[UByte]]
for (i <- 0 until msg.size) {
!(msgData + i) = msg(i)
}

val result = alloc[UByte](32).asInstanceOf[Ptr[UByte]]
HmacExtern.hmac_sha256(
result,
keyData,
keySize,
msgData,
msgSize
)

val res = Array.ofDim[UByte](32)
for (i <- 0 until 32) {
res(i) = (!(result + i)).toUByte
}
res
}
}
}
}

@extern
object HmacExtern {
def hmac_sha256(
hmac: Ptr[UByte],
k: Ptr[UByte],
ksize: CSize,
d: Ptr[UByte],
dsize: CSize
): Unit = extern
}
13 changes: 12 additions & 1 deletion src/test/scala/Test.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import scala.scalanative.unsigned._
import utest._
import sha256.{Sha256, Hkdf}
import sha256.{Sha256, Hkdf, Hmac}

object Sha256EtcTests extends TestSuite {
def bytes2hex(ba: Array[UByte]): String =
Expand Down Expand Up @@ -69,5 +69,16 @@ object Sha256EtcTests extends TestSuite {
r
) ==> "a754786431d51674edc4f04a568a55f37b996db70fa2a795b15e2ea57cfed8be"
}

test("hmac") {
val key = "abcdef".getBytes.map(_.toUByte)
val msg = "123456".getBytes.map(_.toUByte)

val r = Hmac.hmac(key, msg)
r.size ==> 32
bytes2hex(
r
) ==> "ec4a11a5568e5cfdb5fbfe7152e8920d7bad864a0645c57fe49046a3e81ec91d"
}
}
}

0 comments on commit 8dec37c

Please sign in to comment.