如何在java中将Base64编码的字符串转换为UUID

时间:2016-03-25 05:38:22

标签: java encoding base64

这是编码的字符串

YjRmYTJhMGEtYjI0ZC00ZjU4LTg2ZDktNTNiN2I2ODM4YjY3IzU1YjFjNGUzZTRiMGQ4OTUxMGM2YWEyNw

我想为此

生成UUID

2 个答案:

答案 0 :(得分:1)

您可以使用2个功能进行如下转换。 apache commons codec jar有一些使用UUIDBase64进行编码和解码的方法。

链接下载apache commons编解码器jar:http://www.java2s.com/Code/JarDownload/apache-commons/apache-commons-codec-1.4.jar.zip

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();
    }
}

<强>输出:

  

as base64:62346661-3261-3061-2d62-3234642d3466

     

as uuid:eb6df8eb-aeb5-fb7d-bad7-edf4eb5fb677

更多信息,您可以按照教程进行操作:

  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

答案 1 :(得分:0)

上述base64字符串解码为ASCII字符串“ b4fa2a0a-b24d-4f58-86d9-53b7b6838b67#55b1c4e3e4b0d89510c6aa27”,因此:

import org.apache.commons.codec.binary.Base64;
public class Solution {
    private static String uuidFromBase64(String str) {
        Base64 base64 = new Base64(); 
        byte[] bytes = base64.decodeBase64(str);
        String s = new String(bytes);
        String trimmed = s.split("#")[0];
        return trimmed;
    }
}