< prev index next >

src/java.base/share/classes/java/util/UUID.java

Print this page
rev 53213 : imported patch 8216407-java-util-UUID-fromString-accepts-input-that-does-not-match-expected-format

@@ -1,7 +1,7 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this

@@ -192,15 +192,10 @@
      *          If name does not conform to the string representation as
      *          described in {@link #toString}
      *
      */
     public static UUID fromString(String name) {
-        int len = name.length();
-        if (len > 36) {
-            throw new IllegalArgumentException("UUID string too large");
-        }
-
         int dash1 = name.indexOf('-', 0);
         int dash2 = name.indexOf('-', dash1 + 1);
         int dash3 = name.indexOf('-', dash2 + 1);
         int dash4 = name.indexOf('-', dash3 + 1);
         int dash5 = name.indexOf('-', dash4 + 1);

@@ -209,24 +204,23 @@
         // negative, but it's enough to check dash4 and dash5:
         // - if dash1 is -1, dash4 will be -1
         // - if dash1 is positive but dash2 is -1, dash4 will be -1
         // - if dash1 and dash2 is positive, dash3 will be -1, dash4 will be
         //   positive, but so will dash5
-        if (dash4 < 0 || dash5 >= 0) {
-            throw new IllegalArgumentException("Invalid UUID string: " + name);
-        }
 
-        long mostSigBits = Long.parseLong(name, 0, dash1, 16) & 0xffffffffL;
-        mostSigBits <<= 16;
-        mostSigBits |= Long.parseLong(name, dash1 + 1, dash2, 16) & 0xffffL;
-        mostSigBits <<= 16;
-        mostSigBits |= Long.parseLong(name, dash2 + 1, dash3, 16) & 0xffffL;
-        long leastSigBits = Long.parseLong(name, dash3 + 1, dash4, 16) & 0xffffL;
-        leastSigBits <<= 48;
-        leastSigBits |= Long.parseLong(name, dash4 + 1, len, 16) & 0xffffffffffffL;
+        if (dash4 > 0 && dash5 < 0) {
+            long x1 = Long.parseLong(name, 0, dash1, 16);
+            long x2 = Long.parseLong(name, dash1 + 1, dash2, 16);
+            long x3 = Long.parseLong(name, dash2 + 1, dash3, 16);
+            long x4 = Long.parseLong(name, dash3 + 1, dash4, 16);
+            long x5 = Long.parseLong(name, dash4 + 1, name.length(), 16);
 
-        return new UUID(mostSigBits, leastSigBits);
+            if (((x1 >> 32) | ((x2 | x3 | x4) >> 16) | (x5 >> 48)) == 0L) {
+                return new UUID((x1 << 32) | (x2 << 16) | x3, (x4 << 48) | x5);
+            }
+        }
+        throw new IllegalArgumentException("Invalid UUID string: " + name);
     }
 
     // Field Accessor Methods
 
     /**
< prev index next >