UUID.fromString(var) is accepting additional characters in Java

Viewed 129

I have a requirement where I accept a UUID and check whether the UUID is in valid format or not. Package java.util provides a UUID.FromString(var) method which accepts a variable and it throws an exception when it is not in valid format.

For some unknown reasons, it's accepting an additional character and filters it out instead of throwing an exception.

For example,

String var1="BAAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"
UUID.fromString(var1)

Here, there is an additional character B but instead of throwing an exception, it's filtering it out as "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA".

Can anyone help me understand why is this happening?

I am using Java 8.

2 Answers

Historically, it looks like Java's UUID class has been very lenient in what it accepts. This includes too short segments, and too long segments. This behaviour was tightened up somewhat between Java 8 and Java 11 (I didn't want to check Java 9 or 10 to see exactly when), as Java 11 no longer accepts your example (but still accepts too short segments).

I haven't been able to identify the exact bug in the Java bug database that changed this, but there are a lot around this behaviour (example: JDK-8216407 : java.util.UUID.fromString accepts input that does not match expected format), but most of them are either still open, closed as duplicate, or marked as "won't fix" because of backwards compatibility concerns.

I double-checked (javac 11.0.15)

  • and it is behaving as expected.

Here is an example of how I tested it:

I guess that you are not handling the exception properly.

class Example {
    
public static void main(String[] args) {
        // Valid case
        System.out.println(isValidUUID("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"));
        // Invalid cases
        System.out.println(isValidUUID("Cc21a392e-3da6-4cd4-ac9f-9d963b313e22"));
        System.out.println(isValidUUID("BAAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"));
        System.out.println(isValidUUID("AAAA-AAAAAAAAAAAA"));
        System.out.println(isValidUUID("Hope this helps"));
        
    }
    
    /**
      Check if a supplied UUID is valid
    */
    public static boolean isValidUUID(String uuid) {
        try {
            UUID.fromString(uuid);
        } catch (RuntimeException e) {
            return false;
        }
        return true;
    }
}
Related