Scala HMac SHA256

21 Nov
2020

As I repeatedly (e.g. every 2nd year) have to find the right code to generate a HMAC SHA256 hash from a string, I’m sharing this (for me and others) here. The tricky part is the String-Format to 64 chars. Most code I’ve found had this set to 32 chars (like used for MD5) which resulted in too short hashes for certain inputs.

object HMAC {
def generateHMAC(sharedSecret: String, input: String): String = {
val secret = new SecretKeySpec(sharedSecret.getBytes, "HmacSHA256") //Crypto Funs : 'SHA256' , 'HmacSHA1'
val mac = Mac.getInstance("HmacSHA256")
mac.init(secret)
val hashString: Array[Byte] = mac.doFinal(input.getBytes)
// this makes sure that the string is 64chars long and gets padded with 0 if its shorter
String.format("%064x", new BigInteger(1, hashString))
}
}
view raw HMacSha256.scala hosted with ❤ by GitHub

I hope you find this useful!

Comment Form

top