uuid58

uuid58 Specification

1. Introduction

uuid58 is a text encoding for 128-bit UUIDs. It writes the UUID as an unsigned integer in base 58, using the Bitcoin Base58 alphabet, always padded to exactly 22 characters.

f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf  <->  XDY9dmBbcMBXqcRvYw8xJ2

This document defines the encoding so that independent implementations in different languages produce identical results.

1.1. Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 and RFC 8174 when, and only when, they appear in all capitals, as shown here.

All characters in the alphabet and in accepted inputs are ASCII. U+002D is the hyphen (-).

1.2. Scope

This specification defines:

Generating UUIDs is out of scope. An implementation MAY offer a function that generates a random UUID and returns its uuid58 encoding; this specification places no requirements on it beyond the encoding itself.

2. Alphabet

The alphabet is the following 58 characters, in this order:

123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz

The character at position i (zero-based) is the digit with value i. So 1 is 0, A is 9, and z is 57.

The alphabet is the Bitcoin Base58 alphabet. It consists of the digits 1–9, the uppercase letters A–Z except I and O, and the lowercase letters a–z except l. The digit 0 is not included either. These four characters (0, O, I, l) are left out because they are easily confused with each other.

The alphabet is in ascending ASCII order. Section 3.2 relies on this.

3. Encoding

3.1. Algorithm

The input is a 128-bit value V: either 16 bytes read as an unsigned big-endian integer, or an unsigned integer with 0 <= V <= 2^128 - 1.

The output is the 22-character string d[0] d[1] ... d[21] such that:

V = d[0] * 58^21 + d[1] * 58^20 + ... + d[21] * 58^0

where each d[i] is a digit value in 0..57, written as the corresponding alphabet character. Because 58^22 > 2^128, 22 digits are always enough. Leading digits with value 0 are written as 1; they MUST NOT be omitted.

Encoding a 128-bit value never fails. The output is always exactly 22 characters. Section 3.3 covers inputs whose type can hold other values.

Examples:

UUIDuuid58
00000000-0000-0000-0000-0000000000001111111111111111111111
00000000-0000-0000-0000-0000000000011111111111111111111112
f4b247fd-1f87-45d4-aa06-1c6fc0a8dfafXDY9dmBbcMBXqcRvYw8xJ2
ffffffff-ffff-ffff-ffff-ffffffffffffYcVfxkQb6JRzqk5kF2tNLv

YcVfxkQb6JRzqk5kF2tNLv is the largest valid uuid58 string. It is called MAX_UUID58 below.

3.2. Ordering

For any two 128-bit values A and B, comparing encode(A) and encode(B) character by character in ASCII order gives the same result as comparing A and B as integers. This holds because the alphabet is in ascending ASCII order and every encoding has the same length.

Implementations MUST NOT change the alphabet or the padding in a way that breaks this property.

The comparison must be by character code (or byte), as in a binary or C collation. Locale-aware or case-insensitive collations, common as database defaults, do not preserve this order.

Note (non-normative). The order of a platform's native UUID type may differ from this order. For example, Java's UUID.compareTo compares the two halves as signed 64-bit integers, so it sorts ffffffff-ffff-ffff-ffff-ffffffffffff before 00000000-0000-0000-0000-000000000001, while their encodings sort the other way.

3.3. Inputs that are not exactly 128 bits

Some input types can hold values that are not a 128-bit value: a byte sequence of arbitrary length, or an arbitrary-precision or signed integer. An implementation that encodes from such a type MUST NOT truncate, wrap, or pad the input, and MUST reject it as follows:

Types that can only hold 128-bit values, such as a 16-byte array, an unsigned 128-bit integer, a pair of 64-bit integers taken as the high and low halves, or a native UUID type, need no checks.

When converting from a native UUID type, use the 16 bytes in the order of RFC 9562 (network byte order). Some platforms store UUIDs in a different byte order internally; for example, .NET Guid.ToByteArray() returns the first three fields in little-endian order.

4. Decoding

The input is a string S. Decoding either produces a 128-bit value or fails with an error kind from Section 7. An implementation MUST perform the following checks in this order and report the first one that fails:

  1. Length. If S is not exactly 22 characters long, fail with invalid_length.
  2. Characters. If any character of S is not in the alphabet, fail with invalid_character. Matching is case-sensitive.
  3. Range. Compute V = d[0] * 58^21 + ... + d[21] * 58^0. If V > 2^128 - 1, fail with overflow. Equivalently, since all inputs at this step have the same length, fail if S is greater than MAX_UUID58 in ASCII order (Section 3.2).

Otherwise the result is V. An implementation that returns bytes MUST return V as 16 bytes in big-endian order. An implementation that returns a native UUID type MUST build it from those bytes in the order of RFC 9562 (see Section 3.3 for platforms whose native byte order differs).

The order matters when an input fails more than one check. For example, Zzzzzzzzzzzzzzzzzzzzz0 has digits that overflow, but its last character is not in the alphabet, so it fails with invalid_character. An implementation that rejects early, for example by comparing a prefix of S with MAX_UUID58 or by checking whether the first character is greater than Y, MUST still report invalid_character if a later character is not in the alphabet. (An implementation that accumulates V exactly cannot overflow before the last digit, because 58^21 - 1 < 2^128, so it gets this right without special handling.)

Decoding MUST NOT trim whitespace, ignore unknown characters, or accept strings shorter than 22 characters.

4.1. Measuring length

Implementations MUST measure the length of S in one of these units: UTF-16 code units, Unicode code points, or bytes of UTF-8. They MUST NOT measure it in grapheme clusters (user-perceived characters), which count some ASCII sequences such as \r\n as one.

The three allowed units agree for ASCII input. Any input that contains a non-ASCII character is invalid, but depending on the unit it fails either the length check or the character check. For any input that contains a non-ASCII character, an implementation MAY report either invalid_length or invalid_character, whatever unit it uses. This also allows an implementation to reject non-ASCII input before checking the length.

For string types that can hold arbitrary bytes or ill-formed text (such as Go string, Rust &[u8], or PHP and Ruby strings), any byte 0x80 or above, any unpaired surrogate, and any ill-formed UTF-8 or UTF-16 sequence counts as a non-ASCII character: the input MUST be rejected, with either kind.

An implementation MUST NOT map a non-ASCII character to an ASCII one. This includes keeping only its low 7 or 8 bits (U+0141 Ł is not A, even though its low byte is 0x41), applying Unicode normalization, comparing under canonical or compatibility equivalence (U+212A KELVIN SIGN is not K, even though Swift's Character comparison treats them as equal), and classifying digits with Unicode-aware functions (U+FF10 FULLWIDTH DIGIT ZERO is not 0). Compare code units, code points, or bytes directly.

5. UUID Strings

Implementations usually accept and produce UUIDs as text. This section defines those forms. An implementation that only works with 16-byte or 128-bit integer values does not need to implement it.

5.1. Accepted forms

An implementation that encodes from a UUID string MUST accept exactly these two forms, and MUST reject every other input:

A hexadecimal digit is 0–9, a–f, or A–F. Upper and lower case MUST both be accepted, including mixed case within one string.

The 32 hexadecimal digits, read left to right, are the 16 bytes of the UUID in big-endian order.

Other notations, such as braces ({...}), the urn:uuid: prefix, or surrounding whitespace, MUST be rejected. An implementation MAY offer a separate, clearly named function that accepts them.

Parsing a UUID string MUST perform the following checks in this order:

  1. If the length is neither 32 nor 36, fail with invalid_length.
  2. If the string does not match the form for its length, fail with invalid_character. This includes a hyphen in the wrong position and, for a 36-character input, a missing hyphen.

Section 4.1 applies here too: length is measured the same way, and for input that contains a non-ASCII character, an implementation MAY report either invalid_length or invalid_character.

Note (non-normative). Standard-library UUID and integer parsers are usually more lenient than this section allows, so an implementation should not rely on them for validation. For example, Python's uuid.UUID accepts braces, the urn:uuid: prefix, and misplaced hyphens; Python's int(s, 16) accepts a leading + or - and _ between digits; Java's UUID.fromString accepts groups shorter than their normal width; Rust's u128::from_str_radix(s, 16) accepts a leading +, and the uuid crate's Uuid::parse_str accepts braces and the urn:uuid: prefix; and in many regular expression engines $ also matches before a trailing newline. Check every character explicitly instead.

5.2. Produced form

An implementation that decodes to a UUID string MUST produce the hyphenated form in lowercase:

f4b247fd-1f87-45d4-aa06-1c6fc0a8dfaf

6. Validation

An implementation MAY offer a function that checks whether a string is a valid uuid58 string without returning the value. If it does, the function MUST return true exactly when decoding (Section 4) would succeed.

A pattern that checks only the length and the alphabet, such as the regular expression [1-9A-HJ-NP-Za-km-z]{22} matched against the whole string, is not sufficient on its own, because it accepts strings greater than MAX_UUID58. It can serve as the first step, followed by an ASCII comparison with MAX_UUID58 (Section 4, step 3).

When using such a pattern, make sure it matches the entire input. In many regular expression engines, ^...$ also matches when the input ends with a newline, and in some (such as Ruby) ^ and $ match at every line. Use a full-match API or anchors such as \A...\z where available.

7. Errors

This specification defines the following error kinds:

KindRaised byMeaning
invalid_lengthUUID parsing, decoding, encoding from bytesThe input has the wrong length (or contains a non-ASCII character; see Section 4.1).
invalid_characterUUID parsing, decodingThe input has the right length but contains a character that is not allowed in its position (or, for input of any length, contains a non-ASCII character; see Section 4.1).
overflowdecoding, encoding from an integerThe input is well formed but its value is outside 0..2^128 - 1.

How errors are reported (exceptions, result types, error values) is up to each implementation. An implementation SHOULD let callers distinguish the kinds. The wording of error messages is not specified.

Inputs are untrusted, and error messages commonly end up in logs, terminals, and error trackers. An error message SHOULD NOT include the input itself; it MAY include facts about it, such as its length or the position of the first invalid character. An implementation that does include the input SHOULD escape control and non-ASCII characters and SHOULD truncate long input, so that an error message can neither span several lines nor grow with the input.

8. Conformance

An implementation conforms to this specification if it passes every case in vectors.json that applies to the operations it implements.

8.1. Test vector format

{
  "spec_version": "1.1.0",
  "alphabet": "123456789ABC...",
  // Pairs that MUST round-trip in both directions.
  // `uuid` is the produced form (Section 5.2).
  "roundtrip": [
    { "description": "...", "uuid": "00000000-...", "uuid58": "1111..." },
  ],
  "encode": {
    // Additional accepted UUID strings and the uuid58 they encode to.
    "valid": [
      { "description": "...", "input": "F4B2...", "output": "XDY9..." },
    ],
    // UUID strings that MUST be rejected.
    "invalid": [
      {
        "description": "...",
        "input": "...",
        // The input MUST fail with one of these kinds.
        "errors": ["invalid_length"],
        // Optional. Present only on inputs that JavaScript 1.x accepts
        // (Section 9.1), together with the value it returns for them.
        "lenient": true,
        "lenient_output": "XDY9...",
      },
    ],
    // For APIs that encode from a byte sequence of any length (Section 3.3).
    // APIs that take a fixed 16-byte array skip these.
    // `bytes` is the byte sequence written as hexadecimal.
    "invalid_bytes": [
      {
        "description": "...",
        "bytes": "0000...",
        "errors": ["invalid_length"],
      },
    ],
    // For APIs that encode from an arbitrary-precision or signed integer
    // (Section 3.3). `integer` is written in decimal.
    "invalid_integers": [
      { "description": "...", "integer": "-1", "errors": ["overflow"] },
    ],
  },
  "decode": {
    // uuid58 strings that MUST be rejected. Valid ones are in `roundtrip`.
    "invalid": [
      { "description": "...", "input": "...", "errors": ["overflow"] },
    ],
  },
}

An implementation that does not report error kinds only needs to check that each invalid input fails.

JSON strings cannot hold ill-formed text, so vectors.json cannot express the inputs of Section 4.1 that are not valid Unicode. An implementation whose string type can hold arbitrary bytes or unpaired surrogates MUST also test such inputs itself, both for decoding and for UUID string parsing. Examples are a 22-byte input containing 0xFF, an input containing a lone 0x80 or 0xC1 byte, a 36-byte UUID string with 0xFF in place of a hexadecimal digit, or a lone surrogate.

An implementation that works with 16-byte or integer values instead of UUID strings (Section 5) can still use roundtrip: remove the hyphens from uuid and read the 32 hexadecimal digits as 16 bytes in big-endian order (or as an unsigned integer in base 16).

An implementation that works with a native UUID type MUST NOT test only by round-tripping its own values, which would hide a byte-order mistake. It MUST compare the decoded value against uuid, either through the type's canonical text form or through the 16 bytes derived from uuid as above.

encode.valid and encode.invalid test UUID string parsing (Section 5). An implementation that does not parse UUID strings, for example one that only works with a native UUID type, bytes, or integers, skips them. An implementation that parses UUID strings in addition to other inputs MUST test them.

An implementation of validation (Section 6) MUST return true for every uuid58 in roundtrip and false for every input in decode.invalid.

8.2. Regenerating the vectors

vectors.json is generated by generate_vectors.py, an independent reference implementation that uses only the Python standard library. Do not edit vectors.json by hand.

python3 spec/generate_vectors.py          # rewrite vectors.json
python3 spec/generate_vectors.py --check  # fail if vectors.json is stale

9. Known Deviations

9.1. JavaScript @nakanoaas/uuid58 1.x

Before this specification, the JavaScript package accepted any string that becomes 32 hexadecimal digits after removing every -, wherever the hyphens are and however many there are (for example f4b247f-d1f87-45d4-aa06-1c6fc0a8dfaf). This violates Section 5.1.

To stay compatible, 1.x keeps this behavior. The test vectors mark these inputs with "lenient": true and give the value 1.x returns in lenient_output. Version 2.0 and later of the JavaScript package reject them as this specification requires, and expose error kinds through the kind property of their errors. New implementations MUST NOT accept them.

1.x also differs from Section 7 in how it reports errors:

The wording of error messages is not part of this specification, so these are not conformance failures, but they should not be mapped to kinds by parsing the message.