4 ms·
Thinking about it, the above is wrong because it replaces - and _ with A and B which makes it not reversible. This is reversible. You could aolso come up with a
by andrewstuart 2y ago
Thinking about it, the above is wrong because it replaces - and _ with A and B which makes it not reversible. This is reversible. You could aolso come up with a solution that has no - or _ by doing a custom base64 encode with only AZaz and 0 to 9.
If you really want to not have _ or - in your short form UUIDs you could just discard the UUID when you create it if the short form includes those characters and try again.
c22c1dcf-ea74-470e-acbf-b1722e243025 -> wiwdz-p0Rw6sv7FyLiQwJQ (length: 22)
Reversed: c22c1dcf-ea74-470e-acbf-b1722e243025
8702aecb-6d09-4a5e-8cc8-621aada6ed96 -> hwKuy20JSl6MyGIarabtlg (length: 22)
Reversed: 8702aecb-6d09-4a5e-8cc8-621aada6ed96
643a9829-9f91-4b88-80a6-db2c0eb83e8b -> ZDqYKZ-RS4iAptssDrg-iw (length: 22)
Reversed: 643a9829-9f91-4b88-80a6-db2c0eb83e8b
8e7f3c1a-3d19-425e-8803-fe55a296688e -> jn88Gj0ZQl6IA_5VopZojg (length: 22)
Reversed: 8e7f3c1a-3d19-425e-8803-fe55a296688e
1859f017-a5f3-4875-825a-fdd531dfac1a -> GFnwF6XzSHWCWv3VMd-sGg (length: 22)
Reversed: 1859f017-a5f3-4875-825a-fdd531dfac1a
6a153b44-7fca-45b2-b13e-7f45790be7bf -> ahU7RH_KRbKxPn9FeQvnvw (length: 22)
Reversed: 6a153b44-7fca-45b2-b13e-7f45790be7bf
fd6bad83-a0f8-4c7f-baf1-10374be3e8e9 -> _Wutg6D4TH-68RA3S-Po6Q (length: 22)
Reversed: fd6bad83-a0f8-4c7f-baf1-10374be3e8e9
cf2452d4-947b-4b92-a280-ff869e77ba65 -> zyRS1JR7S5KigP-Gnne6ZQ (length: 22)
Reversed: cf2452d4-947b-4b92-a280-ff869e77ba65
import uuid
import base64
def make_short_uuid(data):
return base64.urlsafe_b64encode(data).rstrip(b'=').decode('utf-8')
def reverse_short_uuid(short_uuid):
# Add padding back to make it Base64 decodable
restored = short_uuid + '=' * (-len(short_uuid) % 4)
# Decode the Base64 string back to bytes
return base64.urlsafe_b64decode(restored)
def generate_and_print_uuids():
for _ in range(8):
uuid_obj = uuid.uuid4()
uuid_bytes = uuid_obj.bytes
short_uuid = make_short_uuid(uuid_bytes)
reversed_uuid_bytes = reverse_short_uuid(short_uuid)
print(f'{uuid_obj} -> {short_uuid} (length: {len(short_uuid)})')
print(f'Reversed: {uuid.UUID(bytes=reversed_uuid_bytes)}\n')
generate_and_print_uuids()