Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.UUID.fromString not checking length

Tags:

java

When I looked into the implementation of java.util.UUID.fromString, I found that it doesn't check for the UUID length. Is there any particular reason for this? It only checks the components separated by "-".

String[] components = name.split("-");
        if (components.length != 5)
            throw new IllegalArgumentException("Invalid UUID string: "+name);

Should it also throw IllegalArgumentException when length is not 36?

Currently, without the length checking, numbers are automatically prepended with 0's if less than the component length or shifted if more. The downside is, if one entered a UUID string with a missing digit, it is accepted as valid and prepended with 0. This is hard to debug.

For example, this "12345678-1234-1234-1234-123456789ab" becomes "12345678-1234-1234-1234-0123456789ab". Notice the '0' added? And this "12345678-1234-1234-1234-123456789abcd" becomes "12345678-1234-1234-1234-23456789abcd" with the '1' removed.

To push this even further, the string "1-2-3-4-5" will also be treated as valid and becomes "00000001-0002-0003-0004-000000000005".

Edit: To clarify my question, is this a bug or done on purpose to follow some standard or principle?

like image 710
Adrian M Avatar asked Mar 19 '12 10:03

Adrian M


1 Answers

Only the original authors of the UUID class could tell you why they chose not to check the component lengths in the fromString method, but I suspect they were trying to heed Postel's law:

Be liberal in what you accept, and conservative in what you send.

You can always check the input against a regular expression like this one:

[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}
like image 100
Joni Avatar answered Oct 03 '22 04:10

Joni