Created
July 10, 2022 21:28
-
-
Save SerggioC/4becd0fc7ab8a5ad245ada12d97f255c to your computer and use it in GitHub Desktop.
SHA hash with HMAC256 kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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