Showing posts with label UUID. Show all posts
Showing posts with label UUID. Show all posts

Saturday, December 2, 2017

How to convert Base64 encoded string to UUID in java?

You can convert as below using 2 functions. apache commons codec jar has some methods to encode and decode UUID using Base64.
import java.nio.ByteBuffer;
import java.util.UUID;

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


public class Solution1 {
    public static void main(String[] args) {
        String uuid_str = "YjRmYTJhMGEtYjI0ZC00ZjU4LTg2ZDktNTNiN2I2ODM4YjY3IzU1YjFjNGUzZTRiMGQ4OTUxMGM2YWEyNw";
        String uuid_as_64 = uuidFromBase64(uuid_str);
        System.out.println("as base64: "+uuid_as_64);
        System.out.println("as uuid: "+uuidFromBase64(uuid_as_64));
    }

    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();
    }
}
Output:
as base64: 62346661-3261-3061-2d62-3234642d3466
as uuid: eb6df8eb-aeb5-fb7d-bad7-edf4eb5fb677
For more, you can follow the tutorial:
  1. http://www.baeldung.com/java-base64-encode-and-decode
  2. http://www.tutorialspoint.com/java8/java8_base64.htm
  3. How can I convert a UUID to base64?
  4. Storing UUID as base64 String