Created
April 7, 2023 22:01
Java UUID generation example
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 java.net.NetworkInterface; | |
import java.net.SocketException; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.Enumeration; | |
import java.util.UUID; | |
public class JavaUuidGenerator { | |
public static void main(String[] args) { | |
System.out.println("Version 1 UUID: " + generateVersion1UUID()); | |
System.out.println("Version 4 UUID: " + generateVersion4UUID()); | |
System.out.println("Nil UUID: " + generateNilUUID()); | |
} | |
public static UUID generateVersion1UUID() { | |
try { | |
byte[] mac = getMACAddress(); | |
long timestamp = (System.currentTimeMillis() * 10000) + 0x01B21DD213814000L; | |
timestamp &= ~(0xF000L); | |
timestamp |= 0x1000L; | |
byte[] uuidBytes = new byte[16]; | |
System.arraycopy(mac, 0, uuidBytes, 10, 6); | |
for (int i = 0; i < 8; i++) { | |
uuidBytes[15 - i] = (byte) (timestamp >>> (i * 8)); | |
} | |
MessageDigest md = MessageDigest.getInstance("MD5"); | |
byte[] hash = md.digest(uuidBytes); | |
hash[6] &= 0x0F; | |
hash[6] |= 0x10; | |
hash[8] &= 0x3F; | |
hash[8] |= 0x80; | |
long mostSigBits = 0; | |
long leastSigBits = 0; | |
for (int i = 0; i < 8; i++) { | |
mostSigBits = (mostSigBits << 8) | (hash[i] & 0xFF); | |
leastSigBits = (leastSigBits << 8) | (hash[i + 8] & 0xFF); | |
} | |
return new UUID(mostSigBits, leastSigBits); | |
} catch (SocketException | NoSuchAlgorithmException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public static UUID generateVersion4UUID() { | |
return UUID.randomUUID(); | |
} | |
public static UUID generateNilUUID() { | |
return new UUID(0L, 0L); | |
} | |
private static byte[] getMACAddress() throws SocketException { | |
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); | |
while (interfaces.hasMoreElements()) { | |
NetworkInterface networkInterface = interfaces.nextElement(); | |
if (!networkInterface.isLoopback() && networkInterface.getHardwareAddress() != null) { | |
return networkInterface.getHardwareAddress(); | |
} | |
} | |
throw new RuntimeException("MAC address not found"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment