Skip to content

Instantly share code, notes, and snippets.

@AravindaM
Last active March 2, 2022 20:51
Show Gist options
  • Save AravindaM/795ad9c9f0575fcde07805731790f69c to your computer and use it in GitHub Desktop.
Save AravindaM/795ad9c9f0575fcde07805731790f69c to your computer and use it in GitHub Desktop.
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")
mac.init(secret)
val hashString: Array[Byte] = mac.doFinal(preHashString.getBytes)
new String(hashString.map(_.toChar))
}
}
@Uxito-Ada
Copy link

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")

@codertitto
Copy link

is it possible to generateHMAC without a sharedSecret?

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