Skip to content

Instantly share code, notes, and snippets.

@jstewmon
Last active March 22, 2019 18:29
Show Gist options
  • Save jstewmon/3bc4b0c174b1e3af0d93b986abbc2334 to your computer and use it in GitHub Desktop.
Save jstewmon/3bc4b0c174b1e3af0d93b986abbc2334 to your computer and use it in GitHub Desktop.
Base64Url encoded uuids
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.Base64;
class Main {
public static UUID uuid() {
return UUID.randomUUID();
}
public static String uuidToBase64UrlString(UUID uuid) {
ByteBuffer bb = ByteBuffer.allocate(16)
.putLong(uuid.getMostSignificantBits());
.putLong(uuid.getLeastSignificantBits());
return Base64.getUrlEncoder().withoutPadding().encodeToString(bb.array());
}
public static UUID base64UrlStringToUUID(String uuid) {
ByteBuffer bb = ByteBuffer.wrap(Base64.getUrlDecoder().decode(uuid));
return new UUID(bb.getLong(), bb.getLong());
}
public static void main(String[] args) throws URISyntaxException {
// create a v4 uuid
UUID uuid = uuid();
System.out.println(uuid.toString());
String encodedUuid = uuidToBase64UrlString(uuid);
System.out.println(encodedUuid);
UUID decodedUuid = base64UrlStringToUUID(encodedUuid);
System.out.println(decodedUuid.equals(uuid));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment