Skip to content

Instantly share code, notes, and snippets.

Last active Jul 30, 2021
What would you like to do?
Generate HMAC using SHA256 in Scala
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
Object HMACgen {
def generateHMAC(sharedSecret: String, preHashString: String): String = {
val secret = new SecretKeySpec(sharedSecret.getBytes, "SHA256") //Crypto Funs : 'SHA256' , 'HmacSHA1'
val mac = Mac.getInstance("SHA256")
val hashString: Array[Byte] = mac.doFinal(preHashString.getBytes)
new String(

This comment has been minimized.

Copy link

@fernaspiazu fernaspiazu commented Feb 20, 2018

What value should have preHashString parameter? What does it mean?


This comment has been minimized.

Copy link

@JesseChisholm JesseChisholm commented May 8, 2018

preHashString is just the data string you want to hash. It is often some agreed upon group of fields from the record this hashString will be attached to. Perhaps ...

record.hash = generateHMAC(sharedSecret, record.ip+record.lang+record.timestamp)

Then ship the completed record across the wire somewhere.

The receiver of this record can validate by recalculating the record.hash to see if it was made with the agreed upon sharedSecret key string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment