Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check version 4 UUIDs in python? [closed]

Tags:

python

uuid

I have to check version 4 UUID which is there as common name in a certificate. Is there any python in built function available to check whether UUID prsesnt in the certificate is correct or not and to check its version? If not how to compare version 4 UUID

like image 407
Karma Yogi Avatar asked Dec 19 '18 08:12

Karma Yogi


1 Answers

As Giacomo Alzetta says, UUIDs can be compared as any other object, using ==. The UUID constructor normalises the strings, so that it does not matter if the UUID is in a non-standard form.

import uuid
uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24') == uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24')
# => True
uuid.UUID('302a4299736e4ef384fca9f400e84b24') == uuid.UUID('{302a4299-736e-4ef3-84fc-a9f400e84b24}')
# => True

String comparison will compare the literal strings, which may or may not conform to UUID:

'302a4299-736e-4ef3-84fc-a9f400e84b24' == '302a4299-736e-4ef3-84fc-a9f400e84b24'
# => True
'302a4299736e4ef384fca9f400e84b24' == '{302a4299-736e-4ef3-84fc-a9f400e84b24}'
# => False

You can convert UUIDs to strings using str(x), or strings into UUID objects using uuid.UUID(x) as shown above. Note that you can't compare strings to UUIDs, only strings to strings and UUIDs to UUIDs.

If it really bugs you whether or not an UUID string is in its canonical form, you can try to convert it to an UUID object and back to string (which will give you the canonical form), and compare it to the original:

x = '302a4299-736e-4ef3-84fc-a9f400e84b24'
str(uuid.UUID(x)) == x
# => True
x = '302a4299736e4ef384fca9f400e84b24'
str(uuid.UUID(x)) == x
# => False

However, you really shouldn't care whether a UUID string is canonical - as long as it can be recognised as an UUID string, it should be good enough. If it can't...

uuid.UUID("foo")
# => ValueError: badly formed hexadecimal UUID string

If you need to know the version of the UUID, it's right there in the UUID API:

uuid.UUID('302a4299-736e-4ef3-84fc-a9f400e84b24').version
# => 4
like image 62
Amadan Avatar answered Oct 09 '22 02:10

Amadan