0
# UUID Support
1
2
**⚠️ EXPERIMENTAL API**: The UUID API is experimental and requires opt-in annotation `@ExperimentalUuidApi` to use.
3
4
Secure UUID generation using Web Crypto API with platform-specific implementations for JavaScript environments. This module provides cryptographically secure UUID generation optimized for JavaScript runtime.
5
6
## Capabilities
7
8
### Secure UUID Generation
9
10
Generate cryptographically secure UUIDs using the Web Crypto API.
11
12
```kotlin { .api }
13
/**
14
* Generate cryptographically secure random UUID using Web Crypto API
15
* @ExperimentalUuidApi This API is experimental and may change in future versions
16
*/
17
@ExperimentalUuidApi
18
internal fun secureRandomUuid(): Uuid
19
20
/**
21
* UUID class representing a 128-bit universally unique identifier
22
*/
23
class Uuid {
24
/**
25
* Convert UUID to string representation
26
*/
27
override fun toString(): String
28
29
/**
30
* Convert UUID to byte array
31
*/
32
fun toByteArray(): ByteArray
33
34
/**
35
* Get most significant 64 bits
36
*/
37
val mostSignificantBits: Long
38
39
/**
40
* Get least significant 64 bits
41
*/
42
val leastSignificantBits: Long
43
44
companion object {
45
/**
46
* Parse UUID from string representation
47
*/
48
fun parse(uuidString: String): Uuid
49
50
/**
51
* Create UUID from byte array
52
*/
53
fun fromByteArray(byteArray: ByteArray): Uuid
54
55
/**
56
* Create UUID from most and least significant bits
57
*/
58
fun fromLongs(mostSignificantBits: Long, leastSignificantBits: Long): Uuid
59
60
/**
61
* Generate random UUID (uses secure random if available)
62
*/
63
fun random(): Uuid
64
65
/**
66
* NIL UUID (all zeros)
67
*/
68
val NIL: Uuid
69
}
70
}
71
```
72
73
**Usage Examples:**
74
75
```kotlin
76
import kotlin.uuid.*
77
78
@OptIn(ExperimentalUuidApi::class)
79
fun uuidExample() {
80
// Generate secure random UUID
81
val uuid = secureRandomUuid()
82
console.log("Generated UUID: $uuid")
83
// Output: "f47ac10b-58cc-4372-a567-0e02b2c3d479"
84
85
// Parse UUID from string
86
val uuidString = "123e4567-e89b-12d3-a456-426614174000"
87
val parsedUuid = Uuid.parse(uuidString)
88
console.log("Parsed UUID: $parsedUuid")
89
90
// Generate random UUID (alternative method)
91
val randomUuid = Uuid.random()
92
console.log("Random UUID: $randomUuid")
93
94
// Work with UUID components
95
val testUuid = secureRandomUuid()
96
val mostSig = testUuid.mostSignificantBits
97
val leastSig = testUuid.leastSignificantBits
98
console.log("Most significant bits: ${mostSig.toString(16)}")
99
console.log("Least significant bits: ${leastSig.toString(16)}")
100
101
// Convert to byte array
102
val byteArray = testUuid.toByteArray()
103
val reconstructed = Uuid.fromByteArray(byteArray)
104
console.log("Original: $testUuid")
105
console.log("Reconstructed: $reconstructed")
106
console.log("Equal: ${testUuid == reconstructed}") // true
107
108
// Create from components
109
val customUuid = Uuid.fromLongs(0x123e4567e89b12d3L, 0xa456426614174000L)
110
console.log("Custom UUID: $customUuid")
111
112
// NIL UUID
113
val nilUuid = Uuid.NIL
114
console.log("NIL UUID: $nilUuid") // "00000000-0000-0000-0000-000000000000"
115
```
116
117
### UUID Validation and Formatting
118
119
Validate and format UUID strings with proper error handling.
120
121
```kotlin { .api }
122
/**
123
* Validate UUID string format
124
*/
125
fun String.isValidUuid(): Boolean
126
127
/**
128
* Exception thrown for invalid UUID format
129
*/
130
class IllegalArgumentException : RuntimeException {
131
constructor()
132
constructor(message: String?)
133
constructor(message: String?, cause: Throwable?)
134
}
135
```
136
137
**Usage Examples:**
138
139
```kotlin
140
import kotlin.uuid.*
141
142
// Validate UUID strings
143
val validUuid = "f47ac10b-58cc-4372-a567-0e02b2c3d479"
144
val invalidUuid = "not-a-uuid"
145
146
console.log("Valid: ${validUuid.isValidUuid()}") // true
147
console.log("Invalid: ${invalidUuid.isValidUuid()}") // false
148
149
// Error handling for parsing
150
try {
151
val uuid = Uuid.parse("invalid-uuid-format")
152
} catch (e: IllegalArgumentException) {
153
console.error("Invalid UUID format: ${e.message}")
154
}
155
156
// Safe parsing function
157
fun parseUuidSafely(uuidString: String): Uuid? {
158
return try {
159
if (uuidString.isValidUuid()) {
160
Uuid.parse(uuidString)
161
} else {
162
null
163
}
164
} catch (e: IllegalArgumentException) {
165
null
166
}
167
}
168
169
val safeUuid = parseUuidSafely("f47ac10b-58cc-4372-a567-0e02b2c3d479")
170
console.log("Safely parsed: $safeUuid")
171
```
172
173
### Web Crypto API Integration
174
175
Direct integration with browser Web Crypto API for secure random number generation.
176
177
```kotlin { .api }
178
/**
179
* Web Crypto API interfaces (used internally)
180
*/
181
external interface Crypto {
182
fun getRandomValues(array: Uint8Array): Uint8Array
183
}
184
185
/**
186
* Browser crypto object
187
*/
188
external val crypto: Crypto
189
190
/**
191
* Typed array for unsigned 8-bit integers
192
*/
193
external interface Uint8Array {
194
val length: Int
195
operator fun get(index: Int): Byte
196
operator fun set(index: Int, value: Byte)
197
}
198
```
199
200
**Usage Examples:**
201
202
```kotlin
203
import kotlin.uuid.*
204
205
// The secureRandomUuid() function uses Web Crypto API internally
206
// This provides cryptographically secure randomness in browsers
207
208
// Generate multiple UUIDs
209
val uuids = (1..5).map { secureRandomUuid() }
210
uuids.forEach { uuid ->
211
console.log("UUID $it: $uuid")
212
}
213
214
// Use in data classes
215
data class User(
216
val id: Uuid = secureRandomUuid(),
217
val name: String,
218
val email: String
219
)
220
221
val user = User(name = "Alice", email = "alice@example.com")
222
console.log("User ID: ${user.id}")
223
224
// Session management
225
class Session(
226
val sessionId: Uuid = secureRandomUuid(),
227
val userId: String,
228
val createdAt: Double = js("Date.now()")
229
)
230
231
val session = Session(userId = "user123")
232
console.log("Session: ${session.sessionId}")
233
```
234
235
## Types
236
237
```kotlin { .api }
238
// UUID class
239
class Uuid {
240
val mostSignificantBits: Long
241
val leastSignificantBits: Long
242
243
override fun toString(): String
244
fun toByteArray(): ByteArray
245
246
companion object {
247
fun parse(uuidString: String): Uuid
248
fun fromByteArray(byteArray: ByteArray): Uuid
249
fun fromLongs(mostSignificantBits: Long, leastSignificantBits: Long): Uuid
250
fun random(): Uuid
251
val NIL: Uuid
252
}
253
}
254
255
// UUID generation functions
256
fun secureRandomUuid(): Uuid
257
258
// Validation extensions
259
fun String.isValidUuid(): Boolean
260
261
// Exception types
262
class IllegalArgumentException : RuntimeException
263
264
// Web Crypto API (internal)
265
external interface Crypto {
266
fun getRandomValues(array: Uint8Array): Uint8Array
267
}
268
external val crypto: Crypto
269
external interface Uint8Array
270
```