Question

I'm getting this strange behaviour where sha256 signiture is coming out different for the same input and key every time. Not sure why. Here is the code and some of the printlns.

def apply(algorithm: String, data: String, key: String): Array[Byte] = {

  val _key = Option(key).getOrElse(throw new IllegalArgumentException("Missing key for JWT encryption via " + algorithm))
  val mac: Mac = Mac.getInstance(algorithm)
  val secretKey: SecretKeySpec = new SecretKeySpec(_key.getBytes, algorithm)
  mac.init(secretKey)
  val res = mac.doFinal(data.getBytes)

  println(s"$algorithm $data $key $res $secretKey")
  res
}

Here is the logging from the testsuite using this code:

HmacSHA256 eyJIZXkiOiJmb28ifQ== secretkey [B@4959742d javax.crypto.spec.SecretKeySpec@fa77d7a8
HmacSHA256 eyJIZXkiOiJmb28ifQ== secretkey [B@6a790e37 javax.crypto.spec.SecretKeySpec@fa77d7a8
HmacSHA256 eyJIZXkiOiJmb28ifQ== secretkey [B@2347f330 javax.crypto.spec.SecretKeySpec@fa77d7a8
HmacSHA256 eyJIZXkiOiJmb28ifQ== secretkey [B@5298db1f javax.crypto.spec.SecretKeySpec@fa77d7a8
HmacSHA256 eyJIZXkiOiJmb28ifQ== secretkey [B@5cb80eb0 javax.crypto.spec.SecretKeySpec@fa77d7a8

Why are the signatures all different??

Was it helpful?

Solution

You're not looking at the signature, you're looking at the default toString() method call on an Array of bytes. If you inspect the actual bytes, they should match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top