1 /* 2 * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util; 27 28 import android.compat.Compatibility; 29 import android.compat.annotation.ChangeId; 30 import android.compat.annotation.EnabledSince; 31 32 import dalvik.annotation.compat.VersionCodes; 33 import dalvik.system.VMRuntime; 34 35 import java.security.*; 36 37 /** 38 * A class that represents an immutable universally unique identifier (UUID). 39 * A UUID represents a 128-bit value. 40 * 41 * <p> There exist different variants of these global identifiers. The methods 42 * of this class are for manipulating the Leach-Salz variant, although the 43 * constructors allow the creation of any variant of UUID (described below). 44 * 45 * <p> The layout of a variant 2 (Leach-Salz) UUID is as follows: 46 * 47 * The most significant long consists of the following unsigned fields: 48 * <pre> 49 * 0xFFFFFFFF00000000 time_low 50 * 0x00000000FFFF0000 time_mid 51 * 0x000000000000F000 version 52 * 0x0000000000000FFF time_hi 53 * </pre> 54 * The least significant long consists of the following unsigned fields: 55 * <pre> 56 * 0xC000000000000000 variant 57 * 0x3FFF000000000000 clock_seq 58 * 0x0000FFFFFFFFFFFF node 59 * </pre> 60 * 61 * <p> The variant field contains a value which identifies the layout of the 62 * {@code UUID}. The bit layout described above is valid only for a {@code 63 * UUID} with a variant value of 2, which indicates the Leach-Salz variant. 64 * 65 * <p> The version field holds a value that describes the type of this {@code 66 * UUID}. There are four different basic types of UUIDs: time-based, DCE 67 * security, name-based, and randomly generated UUIDs. These types have a 68 * version value of 1, 2, 3 and 4, respectively. 69 * 70 * <p> For more information including algorithms used to create {@code UUID}s, 71 * see <a href="http://www.ietf.org/rfc/rfc4122.txt"> <i>RFC 4122: A 72 * Universally Unique IDentifier (UUID) URN Namespace</i></a>, section 4.2 73 * "Algorithms for Creating a Time-Based UUID". 74 * 75 * @since 1.5 76 */ 77 public final class UUID implements java.io.Serializable, Comparable<UUID> { 78 79 /** 80 * Explicit serialVersionUID for interoperability. 81 */ 82 @java.io.Serial 83 private static final long serialVersionUID = -4856846361193249489L; 84 85 /* 86 * The most significant 64 bits of this UUID. 87 * 88 * @serial 89 */ 90 private final long mostSigBits; 91 92 /* 93 * The least significant 64 bits of this UUID. 94 * 95 * @serial 96 */ 97 private final long leastSigBits; 98 99 // Android-removed: not using JavaLangAccess.fastUUID. 100 // private static final JavaLangAccess jla = SharedSecrets.getJavaLangAccess(); 101 102 /* 103 * The random number generator used by this class to create random 104 * based UUIDs. In a holder class to defer initialization until needed. 105 */ 106 private static class Holder { 107 static final SecureRandom numberGenerator = new SecureRandom(); 108 } 109 110 // Constructors and Factories 111 112 /* 113 * Private constructor which uses a byte array to construct the new UUID. 114 */ UUID(byte[] data)115 private UUID(byte[] data) { 116 long msb = 0; 117 long lsb = 0; 118 assert data.length == 16 : "data must be 16 bytes in length"; 119 for (int i=0; i<8; i++) 120 msb = (msb << 8) | (data[i] & 0xff); 121 for (int i=8; i<16; i++) 122 lsb = (lsb << 8) | (data[i] & 0xff); 123 this.mostSigBits = msb; 124 this.leastSigBits = lsb; 125 } 126 127 /** 128 * Constructs a new {@code UUID} using the specified data. {@code 129 * mostSigBits} is used for the most significant 64 bits of the {@code 130 * UUID} and {@code leastSigBits} becomes the least significant 64 bits of 131 * the {@code UUID}. 132 * 133 * @param mostSigBits 134 * The most significant bits of the {@code UUID} 135 * 136 * @param leastSigBits 137 * The least significant bits of the {@code UUID} 138 */ UUID(long mostSigBits, long leastSigBits)139 public UUID(long mostSigBits, long leastSigBits) { 140 this.mostSigBits = mostSigBits; 141 this.leastSigBits = leastSigBits; 142 } 143 144 /** 145 * Static factory to retrieve a type 4 (pseudo randomly generated) UUID. 146 * 147 * The {@code UUID} is generated using a cryptographically strong pseudo 148 * random number generator. 149 * 150 * @return A randomly generated {@code UUID} 151 */ randomUUID()152 public static UUID randomUUID() { 153 SecureRandom ng = Holder.numberGenerator; 154 155 byte[] randomBytes = new byte[16]; 156 ng.nextBytes(randomBytes); 157 randomBytes[6] &= 0x0f; /* clear version */ 158 randomBytes[6] |= 0x40; /* set to version 4 */ 159 randomBytes[8] &= 0x3f; /* clear variant */ 160 randomBytes[8] |= 0x80; /* set to IETF variant */ 161 return new UUID(randomBytes); 162 } 163 164 /** 165 * Static factory to retrieve a type 3 (name based) {@code UUID} based on 166 * the specified byte array. 167 * 168 * @param name 169 * A byte array to be used to construct a {@code UUID} 170 * 171 * @return A {@code UUID} generated from the specified array 172 */ nameUUIDFromBytes(byte[] name)173 public static UUID nameUUIDFromBytes(byte[] name) { 174 MessageDigest md; 175 try { 176 md = MessageDigest.getInstance("MD5"); 177 } catch (NoSuchAlgorithmException nsae) { 178 throw new InternalError("MD5 not supported", nsae); 179 } 180 byte[] md5Bytes = md.digest(name); 181 md5Bytes[6] &= 0x0f; /* clear version */ 182 md5Bytes[6] |= 0x30; /* set to version 3 */ 183 md5Bytes[8] &= 0x3f; /* clear variant */ 184 md5Bytes[8] |= 0x80; /* set to IETF variant */ 185 return new UUID(md5Bytes); 186 } 187 188 private static final byte[] NIBBLES; 189 static { 190 byte[] ns = new byte[256]; Arrays.fill(ns, (byte) -1)191 Arrays.fill(ns, (byte) -1); 192 ns['0'] = 0; 193 ns['1'] = 1; 194 ns['2'] = 2; 195 ns['3'] = 3; 196 ns['4'] = 4; 197 ns['5'] = 5; 198 ns['6'] = 6; 199 ns['7'] = 7; 200 ns['8'] = 8; 201 ns['9'] = 9; 202 ns['A'] = 10; 203 ns['B'] = 11; 204 ns['C'] = 12; 205 ns['D'] = 13; 206 ns['E'] = 14; 207 ns['F'] = 15; 208 ns['a'] = 10; 209 ns['b'] = 11; 210 ns['c'] = 12; 211 ns['d'] = 13; 212 ns['e'] = 14; 213 ns['f'] = 15; 214 NIBBLES = ns; 215 } 216 parse4Nibbles(String name, int pos)217 private static long parse4Nibbles(String name, int pos) { 218 byte[] ns = NIBBLES; 219 char ch1 = name.charAt(pos); 220 char ch2 = name.charAt(pos + 1); 221 char ch3 = name.charAt(pos + 2); 222 char ch4 = name.charAt(pos + 3); 223 return (ch1 | ch2 | ch3 | ch4) > 0xff ? 224 -1 : ns[ch1] << 12 | ns[ch2] << 8 | ns[ch3] << 4 | ns[ch4]; 225 } 226 227 /** 228 * Since Android 14 {@link #fromString} does more strict input argument 229 * validation. 230 * 231 * This flag is enabled for apps targeting Android 14+. 232 * 233 * @hide 234 */ 235 @ChangeId 236 @EnabledSince(targetSdkVersion = VersionCodes.UPSIDE_DOWN_CAKE) 237 public static final long ENABLE_STRICT_VALIDATION = 263076149L; 238 239 /** 240 * Creates a {@code UUID} from the string standard representation as 241 * described in the {@link #toString} method. 242 * 243 * @param name 244 * A string that specifies a {@code UUID} 245 * 246 * @return A {@code UUID} with the specified value 247 * 248 * @throws IllegalArgumentException 249 * If name does not conform to the string representation as 250 * described in {@link #toString} 251 * 252 */ fromString(String name)253 public static UUID fromString(String name) { 254 // BEGIN Android-changed: Java 8 behaviour is more lenient and the new implementation 255 // might break apps (b/254278943). 256 // Using old implementation for apps targeting Android older than U. 257 if (!(VMRuntime.getSdkVersion() >= VersionCodes.UPSIDE_DOWN_CAKE 258 && Compatibility.isChangeEnabled(ENABLE_STRICT_VALIDATION))) { 259 return fromStringJava8(name); 260 } 261 262 return fromStringCurrentJava(name); 263 // END Android-changed: Java 8 behaviour is more lenient and the new implementation 264 // might break apps (b/254278943). 265 } 266 267 /** 268 * Extracted for testing purposes only. 269 * @hide 270 */ fromStringCurrentJava(String name)271 public static UUID fromStringCurrentJava(String name) { 272 if (name.length() == 36) { 273 char ch1 = name.charAt(8); 274 char ch2 = name.charAt(13); 275 char ch3 = name.charAt(18); 276 char ch4 = name.charAt(23); 277 if (ch1 == '-' && ch2 == '-' && ch3 == '-' && ch4 == '-') { 278 long msb1 = parse4Nibbles(name, 0); 279 long msb2 = parse4Nibbles(name, 4); 280 long msb3 = parse4Nibbles(name, 9); 281 long msb4 = parse4Nibbles(name, 14); 282 long lsb1 = parse4Nibbles(name, 19); 283 long lsb2 = parse4Nibbles(name, 24); 284 long lsb3 = parse4Nibbles(name, 28); 285 long lsb4 = parse4Nibbles(name, 32); 286 if ((msb1 | msb2 | msb3 | msb4 | lsb1 | lsb2 | lsb3 | lsb4) >= 0) { 287 return new UUID( 288 msb1 << 48 | msb2 << 32 | msb3 << 16 | msb4, 289 lsb1 << 48 | lsb2 << 32 | lsb3 << 16 | lsb4); 290 } 291 } 292 } 293 return fromString1(name); 294 } 295 fromString1(String name)296 private static UUID fromString1(String name) { 297 int len = name.length(); 298 if (len > 36) { 299 throw new IllegalArgumentException("UUID string too large"); 300 } 301 302 int dash1 = name.indexOf('-', 0); 303 int dash2 = name.indexOf('-', dash1 + 1); 304 int dash3 = name.indexOf('-', dash2 + 1); 305 int dash4 = name.indexOf('-', dash3 + 1); 306 int dash5 = name.indexOf('-', dash4 + 1); 307 308 // For any valid input, dash1 through dash4 will be positive and dash5 309 // negative, but it's enough to check dash4 and dash5: 310 // - if dash1 is -1, dash4 will be -1 311 // - if dash1 is positive but dash2 is -1, dash4 will be -1 312 // - if dash1 and dash2 is positive, dash3 will be -1, dash4 will be 313 // positive, but so will dash5 314 if (dash4 < 0 || dash5 >= 0) { 315 throw new IllegalArgumentException("Invalid UUID string: " + name); 316 } 317 318 long mostSigBits = Long.parseLong(name, 0, dash1, 16) & 0xffffffffL; 319 mostSigBits <<= 16; 320 mostSigBits |= Long.parseLong(name, dash1 + 1, dash2, 16) & 0xffffL; 321 mostSigBits <<= 16; 322 mostSigBits |= Long.parseLong(name, dash2 + 1, dash3, 16) & 0xffffL; 323 long leastSigBits = Long.parseLong(name, dash3 + 1, dash4, 16) & 0xffffL; 324 leastSigBits <<= 48; 325 leastSigBits |= Long.parseLong(name, dash4 + 1, len, 16) & 0xffffffffffffL; 326 327 return new UUID(mostSigBits, leastSigBits); 328 } 329 330 /** 331 * Extracted for testing purposes only. 332 * @hide 333 */ fromStringJava8(String name)334 public static UUID fromStringJava8(String name) { 335 String[] components = name.split("-"); 336 if (components.length != 5) 337 throw new IllegalArgumentException("Invalid UUID string: "+ name); 338 for (int i=0; i<5; i++) 339 components[i] = "0x"+components[i]; 340 341 long mostSigBits = Long.decode(components[0]).longValue(); 342 mostSigBits <<= 16; 343 mostSigBits |= Long.decode(components[1]).longValue(); 344 mostSigBits <<= 16; 345 mostSigBits |= Long.decode(components[2]).longValue(); 346 347 long leastSigBits = Long.decode(components[3]).longValue(); 348 leastSigBits <<= 48; 349 leastSigBits |= Long.decode(components[4]).longValue(); 350 351 return new UUID(mostSigBits, leastSigBits); 352 } 353 354 // Field Accessor Methods 355 356 /** 357 * Returns the least significant 64 bits of this UUID's 128 bit value. 358 * 359 * @return The least significant 64 bits of this UUID's 128 bit value 360 */ getLeastSignificantBits()361 public long getLeastSignificantBits() { 362 return leastSigBits; 363 } 364 365 /** 366 * Returns the most significant 64 bits of this UUID's 128 bit value. 367 * 368 * @return The most significant 64 bits of this UUID's 128 bit value 369 */ getMostSignificantBits()370 public long getMostSignificantBits() { 371 return mostSigBits; 372 } 373 374 /** 375 * The version number associated with this {@code UUID}. The version 376 * number describes how this {@code UUID} was generated. 377 * 378 * The version number has the following meaning: 379 * <ul> 380 * <li>1 Time-based UUID 381 * <li>2 DCE security UUID 382 * <li>3 Name-based UUID 383 * <li>4 Randomly generated UUID 384 * </ul> 385 * 386 * @return The version number of this {@code UUID} 387 */ version()388 public int version() { 389 // Version is bits masked by 0x000000000000F000 in MS long 390 return (int)((mostSigBits >> 12) & 0x0f); 391 } 392 393 /** 394 * The variant number associated with this {@code UUID}. The variant 395 * number describes the layout of the {@code UUID}. 396 * 397 * The variant number has the following meaning: 398 * <ul> 399 * <li>0 Reserved for NCS backward compatibility 400 * <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF RFC 4122</a> 401 * (Leach-Salz), used by this class 402 * <li>6 Reserved, Microsoft Corporation backward compatibility 403 * <li>7 Reserved for future definition 404 * </ul> 405 * 406 * @return The variant number of this {@code UUID} 407 */ variant()408 public int variant() { 409 // This field is composed of a varying number of bits. 410 // 0 - - Reserved for NCS backward compatibility 411 // 1 0 - The IETF aka Leach-Salz variant (used by this class) 412 // 1 1 0 Reserved, Microsoft backward compatibility 413 // 1 1 1 Reserved for future definition. 414 return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) 415 & (leastSigBits >> 63)); 416 } 417 418 /** 419 * The timestamp value associated with this UUID. 420 * 421 * <p> The 60 bit timestamp value is constructed from the time_low, 422 * time_mid, and time_hi fields of this {@code UUID}. The resulting 423 * timestamp is measured in 100-nanosecond units since midnight, 424 * October 15, 1582 UTC. 425 * 426 * <p> The timestamp value is only meaningful in a time-based UUID, which 427 * has version type 1. If this {@code UUID} is not a time-based UUID then 428 * this method throws UnsupportedOperationException. 429 * 430 * @throws UnsupportedOperationException 431 * If this UUID is not a version 1 UUID 432 * @return The timestamp of this {@code UUID}. 433 */ timestamp()434 public long timestamp() { 435 if (version() != 1) { 436 throw new UnsupportedOperationException("Not a time-based UUID"); 437 } 438 439 return (mostSigBits & 0x0FFFL) << 48 440 | ((mostSigBits >> 16) & 0x0FFFFL) << 32 441 | mostSigBits >>> 32; 442 } 443 444 /** 445 * The clock sequence value associated with this UUID. 446 * 447 * <p> The 14 bit clock sequence value is constructed from the clock 448 * sequence field of this UUID. The clock sequence field is used to 449 * guarantee temporal uniqueness in a time-based UUID. 450 * 451 * <p> The {@code clockSequence} value is only meaningful in a time-based 452 * UUID, which has version type 1. If this UUID is not a time-based UUID 453 * then this method throws UnsupportedOperationException. 454 * 455 * @return The clock sequence of this {@code UUID} 456 * 457 * @throws UnsupportedOperationException 458 * If this UUID is not a version 1 UUID 459 */ clockSequence()460 public int clockSequence() { 461 if (version() != 1) { 462 throw new UnsupportedOperationException("Not a time-based UUID"); 463 } 464 465 return (int)((leastSigBits & 0x3FFF000000000000L) >>> 48); 466 } 467 468 /** 469 * The node value associated with this UUID. 470 * 471 * <p> The 48 bit node value is constructed from the node field of this 472 * UUID. This field is intended to hold the IEEE 802 address of the machine 473 * that generated this UUID to guarantee spatial uniqueness. 474 * 475 * <p> The node value is only meaningful in a time-based UUID, which has 476 * version type 1. If this UUID is not a time-based UUID then this method 477 * throws UnsupportedOperationException. 478 * 479 * @return The node value of this {@code UUID} 480 * 481 * @throws UnsupportedOperationException 482 * If this UUID is not a version 1 UUID 483 */ node()484 public long node() { 485 if (version() != 1) { 486 throw new UnsupportedOperationException("Not a time-based UUID"); 487 } 488 489 return leastSigBits & 0x0000FFFFFFFFFFFFL; 490 } 491 492 // Object Inherited Methods 493 494 /** 495 * Returns a {@code String} object representing this {@code UUID}. 496 * 497 * <p> The UUID string representation is as described by this BNF: 498 * <blockquote><pre> 499 * {@code 500 * UUID = <time_low> "-" <time_mid> "-" 501 * <time_high_and_version> "-" 502 * <variant_and_sequence> "-" 503 * <node> 504 * time_low = 4*<hexOctet> 505 * time_mid = 2*<hexOctet> 506 * time_high_and_version = 2*<hexOctet> 507 * variant_and_sequence = 2*<hexOctet> 508 * node = 6*<hexOctet> 509 * hexOctet = <hexDigit><hexDigit> 510 * hexDigit = 511 * "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" 512 * | "a" | "b" | "c" | "d" | "e" | "f" 513 * | "A" | "B" | "C" | "D" | "E" | "F" 514 * }</pre></blockquote> 515 * 516 * @return A string representation of this {@code UUID} 517 */ 518 @Override toString()519 public String toString() { 520 // Android-changed: using old implementation. 521 // return jla.fastUUID(leastSigBits, mostSigBits); 522 return (digits(mostSigBits >> 32, 8) + "-" + 523 digits(mostSigBits >> 16, 4) + "-" + 524 digits(mostSigBits, 4) + "-" + 525 digits(leastSigBits >> 48, 4) + "-" + 526 digits(leastSigBits, 12)); 527 } 528 529 /** Returns val represented by the specified number of hex digits. */ digits(long val, int digits)530 private static String digits(long val, int digits) { 531 long hi = 1L << (digits * 4); 532 return Long.toHexString(hi | (val & (hi - 1))).substring(1); 533 } 534 535 /** 536 * Returns a hash code for this {@code UUID}. 537 * 538 * @return A hash code value for this {@code UUID} 539 */ 540 @Override hashCode()541 public int hashCode() { 542 long hilo = mostSigBits ^ leastSigBits; 543 return ((int)(hilo >> 32)) ^ (int) hilo; 544 } 545 546 /** 547 * Compares this object to the specified object. The result is {@code 548 * true} if and only if the argument is not {@code null}, is a {@code UUID} 549 * object, has the same variant, and contains the same value, bit for bit, 550 * as this {@code UUID}. 551 * 552 * @param obj 553 * The object to be compared 554 * 555 * @return {@code true} if the objects are the same; {@code false} 556 * otherwise 557 */ 558 @Override equals(Object obj)559 public boolean equals(Object obj) { 560 if ((null == obj) || (obj.getClass() != UUID.class)) 561 return false; 562 UUID id = (UUID)obj; 563 return (mostSigBits == id.mostSigBits && 564 leastSigBits == id.leastSigBits); 565 } 566 567 // Comparison Operations 568 569 /** 570 * Compares this UUID with the specified UUID. 571 * 572 * <p> The first of two UUIDs is greater than the second if the most 573 * significant field in which the UUIDs differ is greater for the first 574 * UUID. 575 * 576 * @param val 577 * {@code UUID} to which this {@code UUID} is to be compared 578 * 579 * @return -1, 0 or 1 as this {@code UUID} is less than, equal to, or 580 * greater than {@code val} 581 * 582 */ 583 @Override compareTo(UUID val)584 public int compareTo(UUID val) { 585 // The ordering is intentionally set up so that the UUIDs 586 // can simply be numerically compared as two numbers 587 return (this.mostSigBits < val.mostSigBits ? -1 : 588 (this.mostSigBits > val.mostSigBits ? 1 : 589 (this.leastSigBits < val.leastSigBits ? -1 : 590 (this.leastSigBits > val.leastSigBits ? 1 : 591 0)))); 592 } 593 } 594