Created
October 22, 2020 13:49
-
-
Save creasty/921ef1377158e53267cff142d135b24f to your computer and use it in GitHub Desktop.
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
import javax.crypto.Mac | |
import javax.crypto.spec.SecretKeySpec | |
import kotlin.experimental.and | |
import kotlin.experimental.or | |
fun hmacSha256(data: String, key: String): ByteArray { | |
val algorithm = "HmacSHA256" | |
val secretKeySpec = SecretKeySpec(key.toByteArray(), algorithm) | |
val mac = Mac.getInstance(algorithm) | |
mac.init(secretKeySpec) | |
return mac.doFinal(data.toByteArray()) | |
} | |
fun genDeterministicUuidV4(data: String, key: String): String { | |
val bytes = hmacSha256(data, key) | |
// Per 4.4, set bits for version and 'clock_seq_hi_and_reserved' | |
bytes[6] = (bytes[6] and 0x0f.toByte()) or 0x40.toByte() | |
bytes[8] = (bytes[8] and 0x3f.toByte()) or 0x80.toByte() | |
val stringBuilder = StringBuilder() | |
for ((i, b) in bytes.withIndex()) { | |
if (i == 16) break | |
if (i == 4 || i == 6 || i == 8 || i == 10) { | |
stringBuilder.append("-") | |
} | |
stringBuilder.append("%02x".format(b)) | |
} | |
return stringBuilder.toString() | |
} | |
fun main() { | |
println(genDeterministicUuidV4("00001", "henry-keiai-patient")) | |
println(genDeterministicUuidV4("00002", "henry-keiai-patient")) | |
println(genDeterministicUuidV4("00001", "henry-keiai-doctor")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment