Last active
March 22, 2019 18:29
-
-
Save jstewmon/3bc4b0c174b1e3af0d93b986abbc2334 to your computer and use it in GitHub Desktop.
Base64Url encoded uuids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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