SpinalHDL / SpinalCrypto

SpinalHDL - Cryptography libraries
MIT License
47 stars 19 forks source link

Size Width Issues Encountered when using HMAC_SHA256 #19

Open TealerLinkGuo opened 1 month ago

TealerLinkGuo commented 1 month ago

I tried combining SHA2Core_Std and HMACore_Std and created some assignments to test it, here is my code

class HMAC_SHA256() extends Component
{
    val io = new Bundle
    {
        val init  = in Bool()

        val valid = in Bool()
        val ready = out Bool()
        val last  = in Bool()

        val data_size = in UInt(4 bits)
        val msg_data  = in Bits(32 bits)
        val key_data  = in Bits(512 bits)

        val out_data    = out Bits(256 bits)
        val out_valid   = out Bool()
    }

    val sha256_core = new SHA2Core_Std(SHA2_256)
    val hmac_core = new HMACCore_Std(HMACCoreStdConfig(sha256_core.configCore.hashBlockWidth, sha256_core.configCore))

    hmac_core.io.hashCore <> sha256_core.io

    hmac_core.io.hmacCore.init      := io.init
    hmac_core.io.hmacCore.cmd.msg   := io.msg_data
    hmac_core.io.hmacCore.cmd.size  := io.data_size
    hmac_core.io.hmacCore.cmd.last  := io.last
    hmac_core.io.hmacCore.cmd.valid := io.valid
    hmac_core.io.hmacCore.cmd.key   := io.key_data

    io.ready := hmac_core.io.hmacCore.cmd.ready

    io.out_data  := hmac_core.io.hmacCore.rsp.hmac
    io.out_valid := hmac_core.io.hmacCore.rsp.valid
}

When I run it, it reports a size width error

[error] WIDTH MISMATCH (2 bits <- 8 bits) on (toplevel/hmac_core/io_hmacCore_cmd_payload_fragment_size : in UInt[2 bits]) := (toplevel/io_data_size : in UInt[8 bits]) at
[error]     HMAC_SHA256.<init>(hmac_sha256.scala:37)
[error]     Test_HMAC_SHA256$$anonfun$1.apply(hmac_sha256_sim.scala:6)
[error]     Test_HMAC_SHA256$$anonfun$1.apply(hmac_sha256_sim.scala:6)
[error]     spinal.sim.JvmThread.run(SimManager.scala:51)

So I checked the source code of Hmac and found that the width of size is the bitwidth of SHA2Core_Std divided by 8, the bitwidth of SHA2Core_Std is default 32 bits, so my setting is correct. This error makes me very confused

// source code from SpinalCrypto/blob/master/crypto/src/main/scala/spinal/crypto/mac/hmac/HMACCore_Std.scala
.......

/**
  * HMAC Cmd
  */
case class HMACCoreStdCmd(config: HMACCoreStdConfig) extends Bundle {
  val key  = Bits(config.keyWidth)
  val msg  = Bits(config.gHash.dataWidth)
  val size = UInt(log2Up(config.gHash.dataWidth.value / 8) bits)
}

......
Dolu1990 commented 1 month ago

Ahh on this i can't realy help you, i didn't implemented the code.