Skip to content

Instantly share code, notes, and snippets.

@imchao9
Last active August 18, 2019 09:04
Show Gist options
  • Save imchao9/07bb531c9fe9600cc5c5d755730ea8cf to your computer and use it in GitHub Desktop.
Save imchao9/07bb531c9fe9600cc5c5d755730ea8cf to your computer and use it in GitHub Desktop.
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.SignatureException
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
object HmacSha1Signature {
private val HMAC_SHA1_ALGORITHM = "HmacSHA1"
private fun toHexString(bytes: ByteArray): String {
val formatter = Formatter()
for (b in bytes) {
formatter.format("%02x", b)
}
return formatter.toString()
}
@Throws(SignatureException::class, NoSuchAlgorithmException::class, InvalidKeyException::class)
fun calculateRFC2104HMAC(data: String, key: String): String {
val signingKey = SecretKeySpec(key.toByteArray(), HMAC_SHA1_ALGORITHM)
val mac = Mac.getInstance(HMAC_SHA1_ALGORITHM)
mac.init(signingKey)
return toHexString(mac.doFinal(data.toByteArray()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment