Skip to content

Commit

Permalink
WIP Expose HMAC-SHA-256 interface on Android
Browse files Browse the repository at this point in the history
  • Loading branch information
vitoreiji committed Jan 8, 2025
1 parent 3a8782b commit a31da66
Showing 1 changed file with 10 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class AndroidNativeCryptoFacade(
const val AES256_KEY_LENGTH = 256
const val AES256_KEY_LENGTH_BYTES = AES256_KEY_LENGTH / 8

const val HMAC_256 = "HmacSHA256"
const val HMAC_SHA_256 = "HmacSHA256"

/**
* Converts the given byte array to a key.
Expand Down Expand Up @@ -115,12 +115,13 @@ class AndroidNativeCryptoFacade(

}

private fun hmac256(key: ByteArray, data: ByteArray): ByteArray {
val macKey = SecretKeySpec(key, HMAC_256)
val hmac = Mac.getInstance(HMAC_256)
hmac.init(macKey)
return hmac.doFinal(data)
}
}

fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {
val macKey = SecretKeySpec(key, HMAC_SHA_256)
val hmac = Mac.getInstance(HMAC_SHA_256)
hmac.init(macKey)
return hmac.doFinal(data)
}

override suspend fun generateKyberKeypair(seed: DataWrapper): KyberKeyPair {
Expand Down Expand Up @@ -247,7 +248,7 @@ class AndroidNativeCryptoFacade(
val data = tempOut.toByteArray()
out.write(byteArrayOf(1))
out.write(data)
val macBytes = hmac256(subKeys.mKey!!, data)
val macBytes = hmacSha256(subKeys.mKey!!, data)
out.write(macBytes)
} else {
out.write(tempOut.toByteArray())
Expand Down Expand Up @@ -409,7 +410,7 @@ class AndroidNativeCryptoFacade(
val cipherText = tempOut.toByteArray()
val cipherTextWithoutMac = cipherText.copyOfRange(1, cipherText.size - 32)
val providedMacBytes = cipherText.copyOfRange(cipherText.size - 32, cipherText.size)
val computedMacBytes = hmac256(subKeys.mKey!!, cipherTextWithoutMac)
val computedMacBytes = hmacSha256(subKeys.mKey!!, cipherTextWithoutMac)
if (!Arrays.equals(computedMacBytes, providedMacBytes)) {
throw CryptoError("invalid mac")
}
Expand Down

0 comments on commit a31da66

Please sign in to comment.