Simple Solution for guid and UUID

Source: Internet
Author: User

GUID (globals unique identifiers) refers to the number generated on a machine, which ensures that all machines in the same time and space are unique. Generally, the platform provides APIs for generating guids. The generation algorithm is very interesting. It uses Ethernet Card addresses, nanoseconds, chip ID codes, and many possible numbers. The unique defect of GUID is that the generated result string is large.

A guid is a 128-bit integer (16 bytes). When using a unique identifier, you can use this integer between all computers and networks. The GUID format is "XXXXXXXX-XXXX-xxxxxxxxxxxx", where each X is a hexadecimal word in the range of 0-9 or a-f. For example, 337c7f2b-7a34-4f50-9141-bab9e6478cc8 is a valid guid value.

No two computers in the world will generate duplicate guid values. GUID is used to assign a unique identifier to a network or system with multiple nodes and computers. On Windows, GUID is widely used: Registry, class and interface identifiers, databases, and even automatically generated machine names and directory names. A guid can be used to operate a primary key in the background database.

UUID refers to the number generated on a machine, which ensures that all machines in the same time and space are unique. Generally, the platform provides APIs for UUID generation. UUID is calculated according to the standards set by the Open Software Foundation (OSF), and uses Ethernet Card addresses, nanoseconds, chip ID codes, and many possible numbers. The combination of the following parts: the current date and time (the first part of UUID is related to the time. If you generate a uuid in seconds, the first part is different and the rest are the same), the clock sequence, and the globally unique IEEE machine identification number (if there is a nic, it is obtained from the NIC, and no Nic is obtained in other ways ), the unique defect of UUID is that the generated result string is long. The most common UUID standard is Microsoft's guid (globals unique identifiers ).

Two methods are used to generate guid and UUID

Comm log library required

/**
* @ Author Administrator
*
* Todo to change the template for this generated type comment go
* Window-preferences-Java-code style-code templates
*/
Import java.net. inetaddress;
Import java.net. unknownhostexception;
Import java. Security. messagedigest;
Import java. Security. nosuchalgorithmexception;
Import java. Security. securerandom;
Import java. util. Random;

Public class randomguid extends object {
Protected final org. Apache. commons. Logging. Log logger = org. Apache. commons. Logging. logfactory
. Getlog (getclass ());

Public String valuebeforemd5 = "";
Public String valueaftermd5 = "";
Private Static random myrand;
Private Static securerandom mysecurerand;

Private Static string s_id;
Private Static final int pad_below = 0x10;
Private Static final int two_bytes = 0xff;

/*
* Static block to take care of one time securerandom seed.
* It takes a few seconds to initialize securerandom. You might
* Want to consider removing this static block or replacing
* It with a "time since first loaded" seed to reduce this time.
* This block will run only once per JVM instance.
*/

Static {
Mysecurerand = new securerandom ();
Long secureinitializer = mysecurerand. nextlong ();
Myrand = new random (secureinitializer );
Try {
S_id = inetaddress. getlocalhost (). tostring ();
} Catch (unknownhostexception e ){
E. printstacktrace ();
}

}

/*
* Default constructor. With no specification of security option,
* This constructor defaults to lower security, high performance.
*/
Public randomguid (){
Getrandomguid (false );
}

/*
* Constructor with security option. Setting secure true
* Enables each random number generated to be cryptographically
* Strong. Secure false defaults to the standard random function seeded
* With a single cryptographically strong random number.
*/
Public randomguid (Boolean secure ){
Getrandomguid (secure );
}

/*
* Method to generate the random guid
*/
Private void getrandomguid (Boolean secure ){
Messagedigest MD5 = NULL;
Stringbuffer sbvaluebeforemd5 = new stringbuffer (128 );

Try {
MD5 = messagedigest. getinstance ("MD5 ");
} Catch (nosuchalgorithmexception e ){
Logger. Error ("error:" + E );
}

Try {
Long time = system. currenttimemillis ();
Long Rand = 0;

If (secure ){
Rand = mysecurerand. nextlong ();
} Else {
Rand = myrand. nextlong ();
}
Sbvaluebeforemd5.append (s_id );
Sbvaluebeforemd5.append (":");
Sbvaluebeforemd5.append (long. tostring (time ));
Sbvaluebeforemd5.append (":");
Sbvaluebeforemd5.append (long. tostring (RAND ));

Valuebeforemd5 = sbvaluebeforemd5.tostring ();
Md5.update (valuebeforemd5.getbytes ());

Byte [] array = md5.digest ();
Stringbuffer sb = new stringbuffer (32 );
For (Int J = 0; j <array. length; ++ J ){
Int B = array [J] & two_bytes;
If (B <pad_below)
SB. append ('0 ');
SB. append (integer. tohexstring (B ));
}

Valueaftermd5 = sb. tostring ();

} Catch (exception e ){
Logger. Error ("error:" + E );
}
}

/*
* Convert to the standard format for guid
* (Useful for SQL Server uniqueidentifiers, etc .)
* Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
*/
Public String tostring (){
String raw = valueaftermd5.touppercase ();
Stringbuffer sb = new stringbuffer (64 );
SB. append (raw. substring (0, 8 ));
SB. append ("-");
SB. append (raw. substring (8, 12 ));
SB. append ("-");
SB. append (raw. substring (12, 16 ));
SB. append ("-");
SB. append (raw. substring (16, 20 ));
SB. append ("-");
SB. append (raw. substring (20 ));

Return sb. tostring ();
}

// Demonstraton and self test of class
Public static void main (string ARGs []) {
For (INT I = 0; I <100; I ++ ){
Randomguid myguid = new randomguid ();
System. Out. println ("seeding string =" + myguid. valuebeforemd5 );
System. Out. println ("rawguid =" + myguid. valueaftermd5 );
System. Out. println ("randomguid =" + myguid. tostring ());
}
}

}

Similarly

UUID = UUID. randomuuid ();
System. Out. println ("{" + UUID. tostring () + "}");

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.