Skip to content

Instantly share code, notes, and snippets.

@jtryan
Created August 15, 2016 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtryan/359db1f6802ab94b5aeee1236a4d9b7c to your computer and use it in GitHub Desktop.
Save jtryan/359db1f6802ab94b5aeee1236a4d9b7c to your computer and use it in GitHub Desktop.
UUID base 64 Java

from http://stackoverflow.com/questions/772802/storing-uuid-as-base64-string

####Usage

import org.apache.commons.codec.binary.Base64;

String uuid_str = "6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8";
String uuid_as_64 = uuidToBase64(uuid_str);
System.out.println("as base64: "+uuid_as_64);
System.out.println("as uuid: "+uuidFromBase64(uuid_as_64));

####Output

as base64: b8tRS7h4TJ2Vt43Dp85v2A
as uuid: 6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8

####Functions

private static String uuidToBase64(String str) {
    Base64 base64 = new Base64();
    UUID uuid = UUID.fromString(str);
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return base64.encodeBase64URLSafeString(bb.array());
}
private static String uuidFromBase64(String str) {
    Base64 base64 = new Base64(); 
    byte[] bytes = base64.decodeBase64(str);
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    UUID uuid = new UUID(bb.getLong(), bb.getLong());
    return uuid.toString();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment