Generate BASE58 format uuid (Hibernate Base64 format uuid cont.)

Source: Internet
Author: User
Tags uuid


BASE58 Introduction


BASE58 uses a character set of "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", from which it is not difficult to see, Base58 are pure numbers and letters and remove the characters that cause visual confusion (0: Digit zero, O: uppercase O,i: Uppercase i,l: lowercase l). 9 digits + 49 letters = 58. Because there are no special characters, you can automatically recognize the selection when using the mouse double-click or mobile device selection.



BASE58 itself is urlsafe. Although Base64 's Urfsafe mode is better for URL support, it contains "-or _" in the UUID.



The current popular Bitcoin, is the use of Base58check code, is on the basis of Base58 and added security validation mechanism.


Third, BASE58 encoder program


Because BASE58 has only recently emerged, Java and Apache Commons do not contain encoders.


 
package org.noahx.uuid.utils;
 
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
 
/**
 * Created with IntelliJ IDEA.
 * User: noah
 * Date: 8/2/13
 * Time: 10:36 AM
 * To change this template use File | Settings | File Templates.
 */
public class Base58 {
 
    public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
    private static final int[] INDEXES = new int[128];
 
    static {
        for (int i = 0; i < INDEXES.length; i++) {
            INDEXES[i] = -1;
        }
        for (int i = 0; i < ALPHABET.length; i++) {
            INDEXES[ALPHABET[i]] = i;
        }
    }
 
    /**
     * Encodes the given bytes in base58. No checksum is appended.
     */
    public static String encode(byte[] input) {
        if (input.length == 0) {
            return "";
        }
        input = copyOfRange(input, 0, input.length);
        // Count leading zeroes.
        int zeroCount = 0;
        while (zeroCount < input.length && input[zeroCount] == 0) {
            ++zeroCount;
        }
        // The actual encoding.
        byte[] temp = new byte[input.length * 2];
        int j = temp.length;
 
        int startAt = zeroCount;
        while (startAt < input.length) {
            byte mod = divmod58(input, startAt);
            if (input[startAt] == 0) {
                ++startAt;
            }
            temp[--j] = (byte) ALPHABET[mod];
        }
 
        // Strip extra ‘1‘ if there are some after decoding.
        while (j < temp.length && temp[j] == ALPHABET[0]) {
            ++j;
        }
        // Add as many leading ‘1‘ as there were leading zeros.
        while (--zeroCount >= 0) {
            temp[--j] = (byte) ALPHABET[0];
        }
 
        byte[] output = copyOfRange(temp, j, temp.length);
        try {
            return new String(output, "US-ASCII");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);  // Cannot happen.
        }
    }
 
    public static byte[] decode(String input) throws IllegalArgumentException {
        if (input.length() == 0) {
            return new byte[0];
        }
        byte[] input58 = new byte[input.length()];
        // Transform the String to a base58 byte sequence
        for (int i = 0; i < input.length(); ++i) {
            char c = input.charAt(i);
 
            int digit58 = -1;
            if (c >= 0 && c < 128) {
                digit58 = INDEXES[c];
            }
            if (digit58 < 0) {
                throw new IllegalArgumentException("Illegal character " + c + " at " + i);
            }
 
            input58[i] = (byte) digit58;
        }
        // Count leading zeroes
        int zeroCount = 0;
        while (zeroCount < input58.length && input58[zeroCount] == 0) {
            ++zeroCount;
        }
        // The encoding
        byte[] temp = new byte[input.length()];
        int j = temp.length;
 
        int startAt = zeroCount;
        while (startAt < input58.length) {
            byte mod = divmod256(input58, startAt);
            if (input58[startAt] == 0) {
                ++startAt;
            }
 
            temp[--j] = mod;
        }
        // Do no add extra leading zeroes, move j to first non null byte.
        while (j < temp.length && temp[j] == 0) {
            ++j;
        }
 
        return copyOfRange(temp, j - zeroCount, temp.length);
    }
 
    public static BigInteger decodeToBigInteger(String input) throws IllegalArgumentException {
        return new BigInteger(1, decode(input));
    }
 
    //
    // number -> number / 58, returns number % 58
    //
    private static byte divmod58(byte[] number, int startAt) {
        int remainder = 0;
        for (int i = startAt; i < number.length; i++) {
            int digit256 = (int) number[i] & 0xFF;
            int temp = remainder * 256 + digit256;
 
            number[i] = (byte) (temp / 58);
 
            remainder = temp % 58;
        }
 
        return (byte) remainder;
    }
 
    //
    // number -> number / 256, returns number % 256
    //
    private static byte divmod256(byte[] number58, int startAt) {
        int remainder = 0;
        for (int i = startAt; i < number58.length; i++) {
            int digit58 = (int) number58[i] & 0xFF;
            int temp = remainder * 58 + digit58;
 
            number58[i] = (byte) (temp / 256);
 
            remainder = temp % 256;
        }
 
        return (byte) remainder;
    }
 
    private static byte[] copyOfRange(byte[] source, int from, int to) {
        byte[] range = new byte[to - from];
        System.arraycopy(source, from, range, 0, range.length);
 
        return range;
    }
 
 
}
UUID Generation Program


This build UUID program contains two encodings of Base64 (Urlsafe) and Base58.


 
package org.noahx.uuid.util;
 
import org.apache.commons.codec.binary.Base64;
 
import java.nio.ByteBuffer;
import java.util.UUID;
 
public abstract class UuidUtils {
 
    public static String uuid() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }
 
    public static String base64Uuid() {
        UUID uuid = UUID.randomUUID();
        return base64Uuid(uuid);
    }
 
    protected static String base64Uuid(UUID uuid) {
 
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
 
        return Base64.encodeBase64URLSafeString(bb.array());
    }
 
    public static String encodeBase64Uuid(String uuidString) {
        UUID uuid = UUID.fromString(uuidString);
        return base64Uuid(uuid);
    }
 
    public static String decodeBase64Uuid(String compressedUuid) {
 
        byte[] byUuid = Base64.decodeBase64(compressedUuid);
 
        ByteBuffer bb = ByteBuffer.wrap(byUuid);
        UUID uuid = new UUID(bb.getLong(), bb.getLong());
        return uuid.toString();
    }
 
    public static String base58Uuid() {
        UUID uuid = UUID.randomUUID();
        return base58Uuid(uuid);
    }
 
    protected static String base58Uuid(UUID uuid) {
 
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
 
        return Base58.encode(bb.array());
    }
 
    public static String encodeBase58Uuid(String uuidString) {
        UUID uuid = UUID.fromString(uuidString);
        return base58Uuid(uuid);
    }
 
    public static String decodeBase58Uuid(String base58uuid) {
        byte[] byUuid = Base58.decode(base58uuid);
        ByteBuffer bb = ByteBuffer.wrap(byUuid);
        UUID uuid = new UUID(bb.getLong(), bb.getLong());
        return uuid.toString();
    }
}
Effect of generating UUID 1, Base64 effect
M0ISICCxQi6sP-KIq3kFOw
11YozyYYTvKmuUXpRDvoJA
KlZnS-MuT2m3d-the2chxg
8J3SC10AQzqZr6Im8V2xYA
ES1UiFTGTHqn6ADU5YW0aw
1usa208oT1q7FitKbQHH5Q
53aDQZxKTGyqmKCzDnBwYQ
SVVjViEoQXayWB9_JknKqQ
fP6znJIAT1uGMN9HW5o8cw
YR-2-kKmSOubhGr2LpFCgQ


You can see that there is-with _ characters. You can double-click on the UUID contained above to get only the selected part of the effect.


2, the effect of Base58
 
MqJqC2rtZLkuHys6ed2Eai
QrS5w2t5etpRY3zTR1BAEJ
Qd6wcFFVz2ZSQb3voGGj8P
75bJdWMcEh6NhT51D5Uyju
2L7kTgsktxMBKLkfAo2iWC
UX2Twhbt1kstRziqc7iwCR
9tZNKCeR93taLHU6PVy8hN
HSn6JMibca4nG9URWokpwg
8eL4SNz2a4puEW8fD4njsG
GThFxPsdVUoZMfmKoEHwQX
Trziqc7iwcr9tznkcer93talhu6pvy8hnhsn6jmibca4ng9urwokpwg8el4snz2a4puew8fd4njsggthfxpsdvuozmfmkoehwqx


BASE58, like Base64 (Urlsafe), can mark 128-bit UUID data with just 21 or 22 characters. Essentially the same length, looks more comfortable, and of course later uses BASE58 to generate the UUID. UUID Generator with Hibernate



Generate BASE58 format uuid (Hibernate Base64 format uuid cont.)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.