Skip to content

Instantly share code, notes, and snippets.

@kaspernielsen
Last active November 21, 2024 13:23
Show Gist options
  • Save kaspernielsen/060d8d6876bb16377fd5463829a0c8c4 to your computer and use it in GitHub Desktop.
Save kaspernielsen/060d8d6876bb16377fd5463829a0c8c4 to your computer and use it in GitHub Desktop.
MRN to UUID
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;
public class MRNToUUID {
public static UUID createUUIDFromMRN(String mrn) throws Exception {
// Normalize the MRN
String normMRN = mrn.toLowerCase();
// Hash the MRN using SHA-256
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(normMRN.getBytes(StandardCharsets.UTF_8));
// A UUIDv8 accordingly to RFC 9562:
// Most significant bits: custom_a (48 bits) + version (4 bits) + custom_b (12 bits)
long mostSigBits = ((hash[0] & 0xFFL) << 40) | ((hash[1] & 0xFFL) << 32) |
((hash[2] & 0xFFL) << 24) | ((hash[3] & 0xFFL) << 16) |
((hash[4] & 0xFFL) << 8) | (hash[5] & 0xFFL);
mostSigBits = (mostSigBits << 4) | 0x8; // Add version (4 bits: 0b1000 for UUIDv8)
mostSigBits = (mostSigBits << 12) | ((hash[6] & 0xFFL) << 4) | ((hash[7] >> 4) & 0xF); // Add custom_b (12 bits)
// Least significant bits: variant (2 bits) + custom_c (62 bits)
long leastSigBits = ((hash[7] & 0x0FL) << 60) | ((hash[8] & 0xFFL) << 52) |
((hash[9] & 0xFFL) << 44) | ((hash[10] & 0xFFL) << 36) |
((hash[11] & 0xFFL) << 28) | ((hash[12] & 0xFFL) << 20) |
((hash[13] & 0xFFL) << 12) | ((hash[14] & 0xFFL) << 4) | ((hash[15] >> 4) & 0xF);
leastSigBits &= 0x3FFFFFFFFFFFFFFFL; // Clear variant bits
leastSigBits |= 0x8000000000000000L; // Set variant to 0b10
return new UUID(mostSigBits, leastSigBits);
}
public static void main(String[] args) throws Exception {
String mrn = "urn:mrn:dk:atons:some-dataset";
UUID uuid = createUUIDFromMRN(mrn);
System.out.println("MRN: " + mrn);
System.out.println("UUID: " + uuid.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment