Skip to content

Instantly share code, notes, and snippets.

@SerggioC
Created July 10, 2022 21:28
Show Gist options
  • Save SerggioC/4becd0fc7ab8a5ad245ada12d97f255c to your computer and use it in GitHub Desktop.
Save SerggioC/4becd0fc7ab8a5ad245ada12d97f255c to your computer and use it in GitHub Desktop.
SHA hash with HMAC256 kotlin
private fun generateHashWithHmac256(message: String): String? {
try {
val key = BuildConfig.HASH
val bytes = hmac(key.toByteArray(), message.toByteArray())
if (bytes != null) return bytesToHex(bytes)
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun hmac(key: ByteArray, message: ByteArray): ByteArray? {
try {
val mac = Mac.getInstance("HmacSHA256")
mac.init(SecretKeySpec(key, "HmacSHA256"))
return mac.doFinal(message)
} catch (e: NoSuchAlgorithmException) {
e.printStackTrace()
} catch (e: InvalidKeyException) {
e.printStackTrace()
}
return null
}
private fun bytesToHex(bytes: ByteArray): String {
val result = bytes.joinToString(separator = "") { eachByte ->
"%02x".format(eachByte)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment