Published 2022-06-03
Convert UUID To BASE64 and vice-versa
The programs convert uuidToBase64 and vice-versa.
import org.apache.commons.codec.binary.Base64;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class RunJavaProgram {
public static void getValue() {
try {
// select token from authtoken where user_id = ;
List strList = new ArrayList<>();
strList.add("a4a6c4ed-86b2-452e-bb0c-d7593e1fd0f6");
strList.add("a8a0f8b4-ae16-4607-86d5-055d87f83d24"); // 635
strList.add("1e5f9348-b979-4fa9-9998-b67b61128874"); // 636
strList.forEach(s -> System.out.println(s + "::Decrypted Token - " + uuidToBase64(s)));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* Convert UUID to Base64
* http://stackoverflow.com/questions/772802/storing-uuid-as-base64-string
*
* @param str
* @return
*/
public 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());
}
/**
* Convert Base64 to UUID
*
* @param str
* @return
*/
public static String uuidFromBase64(String str) {
Base64 base64 = new Base64();
try {
byte[] bytes = base64.decodeBase64(str);
ByteBuffer bb = ByteBuffer.wrap(bytes);
UUID uuid = new UUID(bb.getLong(), bb.getLong());
return uuid.toString();
} catch (Exception e) {
return "";
}
}
}