Генерация уникального id java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A unique string ID generator for Java.

License

aventrix/jnanoid

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A unique string ID generator for Java.

JNanoID uses Java’s SecureRandom to generate cryptographically strong random IDs with a proper distribution of characters.

JNanoID generates compact IDs with just 21 characters. By using a larger alphabet than UUID, JNanoID can generate a greater number of unique IDs, when compared to UUID, with fewer characters (21 versus 36).

JNanoID uses URL-friendly characters ( A-Za-z0-9_- ). Perfect for unique identifiers in web applications.

JNanoID is fully customizable. All default options may be overridden. Supply your own Random Number Generator, alphabet, or size.

JNanoID is thoroughly tested with JUnit.

The most recent release is JNanoId 2.0.0.

dependency> groupId>com.aventrix.jnanoidgroupId> artifactId>jnanoidartifactId> version>2.0.0version> dependency>
compile 'com.aventrix.jnanoid:jnanoid:2.0.0'

JNanoId provides one easy-to-use utility class ( NanoIdUtils ) with two methods to generate IDs.

Standard IDs — randomNanoId()

The default method creates secure, url-friendly, unique ids. It uses a url-friendly alphabet ( A-Za-z0-9_- ), a secure random number generator, and generates a unique ID with 21 characters.

String id = NanoIdUtils.randomNanoId(); // "ku-qLNv1wDmIS5_EcT3j7"

Custom IDs — NanoIdUtils.randomNanoId(random, alphabet, size);

An additional method allows you to generate custom IDs by specifying your own random number generator, alphabet, or size.

// Use a faster, but non-secure, random generator Random random = new Random(); // Use a custom alphabet containing only a, b, and c char[] alphabet = 'a','b','c'>; // Make IDs 10 characters long int size = 10; String id = NanoIdUtils.randomNanoId(random, alphabet, 10); // "babbcaabcb"

Based on the original NanoId for JavaScript by Andrey Sitnik.

Other Programming Languages

Also, a CLI tool is available to generate IDs from the command line.

About

A unique string ID generator for Java.

Источник

Генерация уникального id java

When identifiers are used solely within a database, their generation should be left to the database itself. (See Statement.getGeneratedKeys .)

Unique identifiers which are «published» in some way may need special treatment, since the identifier may need to be difficult to guess or forge. A typical example is the value of a cookie used as a session identifier — simply using a series of consecutive integers is generally unacceptable, since one user could easily impersonate another by altering the value of the cookie to some nearby integer.

Style 1 — UUID

Starting with Java 5, the UUID class provides a simple means for generating unique ids. The identifiers generated by UUID are actually universally unique identifiers.

import java.util.UUID; public class GenerateUUID < public static final void main(String. args)< //generate random UUIDs UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); log("UUID One: " + idOne); log("UUID Two: " + idTwo); > private static void log(Object object) < System.out.println( String.valueOf(object) ); >>
>java -cp . GenerateUUID UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00 UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889

If Java 5 is not available, then there are other more laborious ways to generate unique ids (see below).

Style 2 — SecureRandom and MessageDigest

The following method uses SecureRandom and MessageDigest :

  • upon startup, initialize SecureRandom (this may be a lengthy operation)
  • when a new identifier is needed, generate a random number using SecureRandom
  • create a MessageDigest of the random number
  • encode the byte[] returned by the MessageDigest into some acceptable textual form
  • check if the result is already being used; if it’s not already taken, it’s suitable as a unique identifier
  • is of fixed length
  • does not allow the original input to be easily recovered (in fact, this is very hard)
  • does not uniquely identify the input; however, similar input will produce dissimilar message digests
import java.security.SecureRandom; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class GenerateId < public static void main (String. arguments) < try < //Initialize SecureRandom //This is a lengthy operation, to be done only upon //initialization of the application SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); //generate a random number String randomNum = Integer.valueOf(prng.nextInt()).toString(); //get its digest MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] result = sha.digest(randomNum.getBytes()); System.out.println("Random number: " + randomNum); System.out.println("Message digest: " + hexEncode(result)); > catch (NoSuchAlgorithmException ex) < System.err.println(ex); >> /** * The byte[] returned by MessageDigest does not have a nice * textual representation, so some form of encoding is usually performed. * * This implementation follows the example of David Flanagan's book * "Java In A Nutshell", and converts a byte array into a String * of hex characters. * * Another popular alternative is to use a "Base64" encoding. */ static private String hexEncode(byte[] input)< StringBuilder result = new StringBuilder(); char[] digits = '0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'>; for (int idx = 0; idx < input.length; ++idx) < byte b = input[idx]; result.append(digits[ (b&0xf0) >> 4 ]); result.append(digits[ b&0x0f]); > return result.toString(); > >

>java -cp . GenerateId
Random number: -1103747470
Message digest: c8fff94ba996411079d7114e698b53bac8f7b037

Style 3 — UID

  • the host takes more than one millisecond to reboot
  • the host’s clock is never set to run backwards
import java.rmi.server.UID; public class UniqueId < /** * Build and display some UID objects. */ public static void main (String. arguments) < for (int idx=0; idx10; ++idx)< UID userId = new UID(); System.out.println("User Id: " + userId); > > >

User Id: 3179c3:ec6e28a7ef:-8000
User Id: 3179c3:ec6e28a7ef:-7fff
User Id: 3179c3:ec6e28a7ef:-7ffe
User Id: 3179c3:ec6e28a7ef:-7ffd
User Id: 3179c3:ec6e28a7ef:-7ffc
User Id: 3179c3:ec6e28a7ef:-7ffb
User Id: 3179c3:ec6e28a7ef:-7ffa
User Id: 3179c3:ec6e28a7ef:-7ff9
User Id: 3179c3:ec6e28a7ef:-7ff8
User Id: 3179c3:ec6e28a7ef:-7ff7

Clearly, these are not secure identifiers — knowing one, it’s easy to guess another.

Java Practices 3.012
© 2023 John O’Hanley
Source Code | Contact | License | RSS
Individual code snippets have a BSD license
Over 1,000,000 unique IPs last year
Last updated 2023-01-03
— In Memoriam : Bill Dirani —

Источник

icella / CurrentTimeId.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* The object creation time can be set to object’s identifier property.
* For this purpose, System.currentTimeMillis() can be used. However,
* two or more objects may be created in a single millisecond.
* In this case, these objects will have the same id which is unacceptable.
* One way to cope with this problem is to use System.nanoTime().
* Even if the nano time is the smallest interval we can use, it does not
* also guarantee the uniqueness. To provide unique time stamps,
* I got help from AtomicReference class as follows.
*/
import java . util . concurrent . atomic . AtomicReference ;
public class CurrentTimeId
private static AtomicReference < Long >currentTime =
new AtomicReference <>( System . currentTimeMillis ());
public static Long nextId ()
return currentTime . accumulateAndGet ( System . currentTimeMillis (),
( prev , next ) -> next > prev ? next : prev + 1 )
>
>
/**
* Note that accumulateAndGet method is available since Java 8.
* If you use earlier versions you can implement the following method.
*/
import java . util . concurrent . atomic . AtomicReference ;
public class CurrentTimeId
private static AtomicReference < Long >currentTime =
new AtomicReference <>( System . currentTimeMillis ());
public static Long nextId ()
Long prev ;
Long next = System . currentTimeMillis ();
do
prev = currentTime . get ();
next = next > prev ? next : prev + 1 ;
> while (! currentTime . compareAndSet ( prev , next ));
return next ;
>
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* The simplest way of id generation is to maintain an id counter.
* The counter is actually an integer (mostly a Java long) that is
* incremented at each generation.
*
* The IdCounter below, holds a counter and provides the synchronized
* nextId() method returning the next value of the counter.
* Synchronization is crucial to guard your counter against concurrent
* accesses in multithreaded applications.
*/
public class IdCounter
private static long counter = 0 ;
public static synchronized long nextId ()
return ++ counter ;
>
>
/**
* With Java 1.5+, a better way is using atomics like AtomicLong which
* are already thread-safe in nature. So, you don’t need an explicit synchronization.
*/
import java . util . concurrent . atomic . AtomicLong ;
public class AtomicIdCounter
private static AtomicLong counter = new AtomicLong ( 0 );
public static long nextId ()
return counter . incrementAndGet ();
>
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* Instances of java.rmi.server.UID class generates serializable identifiers
* which are unique on the host they are produced. The host must meet two conditions for uniqueness:
*
* Reboot time must be greater than 1 millisecond
* Its system clock is never set backward
* next class generates a different UID string at each nextUID() call (sample UID: -61bdd364:14a9f9c3782:-8000).
*/
import java . rmi . server . UID ;
public class UIDGenerator
public static String nextUID ()
return new UID (). toString ()
>
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* Our previous solution, UID, generates unique strings on the host.
* They are not globally unique. So, two JVM instances may produce same UIDs.
* If you need universally unique identifiers you can use java.util.
* UUID (Universally Unique IDentifier) class.
*
* The nextUUID() method below generates a different UUID (or GUID) string at
* each call (sample UUID: 251baa74-dc82-4e46-ae58-d7479c06eff5)
*/
import java . util . UUID ;
public class UUIDGenerator
public static String nextUUID ()
return UUID . randomUUID (). toString ();
>
>

Источник

Читайте также:  Java сгенерировать случайную строку
Оцените статью