Skip to content

Instantly share code, notes, and snippets.

@noob9527
Created August 24, 2018 05:33
Show Gist options
  • Save noob9527/1a5a7f921b4265a371ffe95ca87ca471 to your computer and use it in GitHub Desktop.
Save noob9527/1a5a7f921b4265a371ffe95ca87ca471 to your computer and use it in GitHub Desktop.
kotlin Hmac
package com.boosal.ccbba.util
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
object Hmac {
fun digest(
msg: String,
key: String,
alg: String = "HmacSHA256"
): String {
val signingKey = SecretKeySpec(key.toByteArray(), alg)
val mac = Mac.getInstance(alg)
mac.init(signingKey)
val bytes = mac.doFinal(msg.toByteArray())
return format(bytes)
}
private fun format(bytes: ByteArray): String {
val formatter = Formatter()
bytes.forEach { formatter.format("%02x", it) }
return formatter.toString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment