Skip to content

Instantly share code, notes, and snippets.

@johandahlberg
Created June 23, 2016 17:15
Show Gist options
  • Save johandahlberg/e57baac5548885625c38fe09d7fc90fe to your computer and use it in GitHub Desktop.
Save johandahlberg/e57baac5548885625c38fe09d7fc90fe to your computer and use it in GitHub Desktop.
class SHA1VerificationService {
private val secret = "<your key>"
private def computeSHA1Hash(payloadBytes: Array[Byte], secret: String): String = {
val HMAC_SHA1_ALGORITHM = "HmacSHA1"
val secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA1_ALGORITHM)
val mac = Mac.getInstance(HMAC_SHA1_ALGORITHM)
mac.init(secretKeySpec)
val result: Array[Byte] = mac.doFinal(payloadBytes)
val computedHash = Hex.encodeHexString(result)
computedHash
}
def verifyPayload(payloadBytes: Array[Byte], expected: String): Boolean = {
val computedHash = computeSHA1Hash(payloadBytes, secret)
Logger.debug(s"Computed hash: $computedHash")
val matched = computedHash == expected
if (!matched)
Logger.warn(s"Payload could not be verified. Computed: $computedHash and expected: $expected")
matched
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment