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") | |
mac.init(secret) | |
val hashString: Array[Byte] = mac.doFinal(preHashString.getBytes) | |
new String(hashString.map(_.toChar)) | |
} | |
} |
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.
The code in line 8
val mac = Mac.getInstance("SHA256")
does not work for me, which will raise an error like:
Exception in thread "main" java.security.NoSuchAlgorithmException: Algorithm SHA256 not available at javax.crypto.Mac.getInstance(Mac.java:181)
The feasible algorithm specification for me is like:
val mac = Mac.getInstance("HmacSHA256")
is it possible to generateHMAC without a sharedSecret?
What value should have preHashString parameter? What does it mean?