Skip to content

Adding support for randomUUID #197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 0.5.9
* Added support for `randomUUID`.

# 0.5.8
* All classes previously annotated `@sealed` are now `final`!
* Migrate from Gradle Imperative Apply to [Gradle Plugin DSL](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply).
Expand Down
7 changes: 7 additions & 0 deletions lib/src/crypto_subtle.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ extension type JSCrypto(JSObject _) implements JSObject {

/// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
external JSTypedArray getRandomValues(JSTypedArray array);

/// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
external JSString randomUUID();
}

/// The `window.crypto.subtle` object.
Expand Down Expand Up @@ -400,6 +403,10 @@ TypedData getRandomValues(TypedData array) {
return array;
}

String randomUUID() {
return window.crypto.randomUUID().toDart;
}

Future<ByteBuffer> decrypt(
Algorithm algorithm,
JSCryptoKey key,
Expand Down
24 changes: 24 additions & 0 deletions lib/src/impl_ffi/impl_ffi.random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,28 @@ final class _RandomImpl implements RandomImpl {
dest.setAll(0, out.asTypedList(dest.length));
});
}

@override
String randomUUID() {
return _Scope.sync((scope) {
final out = scope<ffi.Uint8>(16);
_checkOp(ssl.RAND_bytes(out, 16) == 1);

var bytes = out.asTypedList(16);
Comment on lines +37 to +40
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe, we could just use fillRandomBytes, then we have less FFI stuff going on.


// Set the 4 most significant bits of bytes[6] to 0100.
bytes[6] = (bytes[6] & 0x0F) | 0x40;

// Set the 2 most significant bits of bytes[8] to 10.
bytes[8] = (bytes[8] & 0x3F) | 0x80;

return bytes
.map((e) => e.toRadixString(16).padLeft(2, '0'))
.join()
.replaceAllMapped(
RegExp(r'(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})'),
(m) => '${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}',
);
Comment on lines +49 to +54
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've done this other places the classical implementation is:

final bytes = _randomBytes(16);
  // Set V4 bits according to:
  // https://tools.ietf.org/html/rfc4122#section-4.4
  bytes[6] = (bytes[6] & 0x0f) | 0x40;
  bytes[8] = (bytes[8] & 0x3f) | 0x80;

  // Encode as UUIDv4
  final s = hex.encode(bytes).substring;
  return '${s(0, 8)}-${s(8, 12)}-${s(12, 16)}-${s(16, 20)}-${s(20)}';

Maybe, using toRadixString is nicer, since it avoids a dependency on package:convert.

});
}
}
1 change: 1 addition & 0 deletions lib/src/impl_interface/impl_interface.random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ part of 'impl_interface.dart';

abstract interface class RandomImpl {
void fillRandomBytes(TypedData destination);
String randomUUID();
}
14 changes: 14 additions & 0 deletions lib/src/impl_js/impl_js.random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,18 @@ final class _RandomImpl implements RandomImpl {
throw _translateJavaScriptException();
}
}

@override
String randomUUID() {
try {
return subtle.randomUUID();
} on Error catch (e) {
final errorName = e.toString();
if (errorName != 'JavaScriptError') {
rethrow;
}

throw _translateJavaScriptException();
}
}
}
5 changes: 5 additions & 0 deletions lib/src/impl_stub/impl_stub.random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,9 @@ final class _RandomImpl implements RandomImpl {
void fillRandomBytes(TypedData destination) {
throw UnimplementedError('Not implemented');
}

@override
String randomUUID() {
throw UnimplementedError('Not implemented');
}
}
19 changes: 19 additions & 0 deletions lib/src/testing/webcrypto/random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ void isNotAllZero(TypedData data) {
check(data.buffer.asUint8List().any((b) => b != 0));
}

void isValidUUID(String uuid) {
check(uuid.length == 36);
check(uuid[8] == '-');
check(uuid[13] == '-');
check(uuid[18] == '-');
check(uuid[23] == '-');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check the bits too

}

void main() => tests().runTests();

/// Tests, exported for use in `../run_all_tests.dart`.
Expand Down Expand Up @@ -83,5 +91,16 @@ List<({String name, Future<void> Function() test})> tests() {
isNotAllZero(data);
});

test('randomUUID: 100 UUIDs', () async {
final uuids = <String>{};
for (var i = 0; i < 100; i++) {
final uuid = randomUUID();
isValidUUID(uuid);
check(uuids.add(uuid));
}

check(uuids.length == 100);
});

return tests;
}
15 changes: 15 additions & 0 deletions lib/src/webcrypto/webcrypto.random.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,18 @@ void fillRandomBytes(

webCryptImpl.random.fillRandomBytes(destination);
}

/// Generate a cryptographically random UUID.
///
/// **Example**
/// ```dart
/// import 'package:webcrypto/webcrypto.dart';
///
/// // Generate a random UUID.
/// void main() {
/// final uuid = randomUUID();
/// print(uuid);
/// }
///
/// ```
String randomUUID() => webCryptImpl.random.randomUUID();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This generates a UUIDv4, there is a specification let's explain that:
https://tools.ietf.org/html/rfc4122#section-4.4

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name of the function in Dart should follow conventions:
https://dart.dev/effective-dart/style#do-capitalize-acronyms-and-abbreviations-longer-than-two-letters-like-words

randomUuid(), however, ugly 🙈

We could choose to just call it uuid(), I don't know. We do change names from Javascript when implementing them in Dart, like how getRandomValues became fillRandomBytes.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@HamdaanAliQuatil any thoughts on the name?

Copy link
Collaborator

@HamdaanAliQuatil HamdaanAliQuatil Apr 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

uuid() looks good.

To add to this - based on the last discussion on randomUUID on w3c, support for UUIDv7 (or other variants), if added, would be in the form of parameters.

If someday webcrypto introduces ULID, it will likely be another in another class and that would be an issue for another day.

As for now, and for the near future as well, uuid() solves our purpose.