源码下载链接:http://pan.baidu.com/s/1jGCEWlC
扫扫关注“茶爸爸”微信公众号

坚持最初的执着,从不曾有半点懈怠,为优秀而努力,为证明自己而活。

/*

 * RandomGUID

 * @version 1.2.1 11/05/02

 * @author Marc A. Mnich

 *

 * From www.JavaExchange.com, Open Software licensing

 *

 * 11/05/02 -- Performance enhancement from Mike Dubman. 

 *             Moved InetAddr.getLocal to static block.  Mike has measured

 *             a 10 fold improvement in run time.

 * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object

 *             caused duplicate GUIDs to be produced.  Random object

 *             is now only created once per JVM.

 * 01/19/02 -- Modified random seeding and added new constructor

 *             to allow secure random feature.

 * 01/14/02 -- Added random function seeding with JVM run time

 *

 */



importjava.net.*;

importjava.util.*;

importjava.security.*;



/*

 * In the multitude of java GUID generators, I found none that

 * guaranteed randomness.  GUIDs are guaranteed to be globally unique

 * by using ethernet MACs, IP addresses, time elements, and sequential

 * numbers.  GUIDs are not expected to be random and most often are

 * easy/possible to guess given a sample from a given generator.

 * SQL Server, for example generates GUID that are unique but

 * sequencial within a given instance.

 *

 * GUIDs can be used as security devices to hide things such as

 * files within a filesystem where listings are unavailable (e.g. files

 * that are served up from a Web server with indexing turned off).

 * This may be desireable in cases where standard authentication is not

 * appropriate. In this scenario, the RandomGUIDs are used as directories.

 * Another example is the use of GUIDs for primary keys in a database

 * where you want to ensure that the keys are secret.  Random GUIDs can

 * then be used in a URL to prevent hackers (or users) from accessing

 * records by guessing or simply by incrementing sequential numbers.

 *

 * There are many other possiblities of using GUIDs in the realm of

 * security and encryption where the element of randomness is important.

 * This class was written for these purposes but can also be used as a

 * general purpose GUID generator as well.

 *

 * RandomGUID generates truly random GUIDs by using the system's

 * IP address (name/IP), system time in milliseconds (as an integer),

 * and a very large random number joined together in a single String

 * that is passed through an MD5 hash.  The IP address and system time

 * make the MD5 seed globally unique and the random number guarantees

 * that the generated GUIDs will have no discernable pattern and

 * cannot be guessed given any number of previously generated GUIDs.

 * It is generally not possible to access the seed information (IP, time,

 * random number) from the resulting GUIDs as the MD5 hash algorithm

 * provides one way encryption.

 *

 * ----> Security of RandomGUID: <-----

 * RandomGUID can be called one of two ways -- with the basic java Random

 * number generator or a cryptographically strong random generator

 * (SecureRandom).  The choice is offered because the secure random

 * generator takes about 3.5 times longer to generate its random numbers

 * and this performance hit may not be worth the added security

 * especially considering the basic generator is seeded with a

 * cryptographically strong random seed.

 *

 * Seeding the basic generator in this way effectively decouples

 * the random numbers from the time component making it virtually impossible

 * to predict the random number component even if one had absolute knowledge

 * of the System time.  Thanks to Ashutosh Narhari for the suggestion

 * of using the static method to prime the basic random generator.

 *

 * Using the secure random option, this class compies with the statistical

 * random number generator tests specified in FIPS 140-2, Security

 * Requirements for Cryptographic Modules, secition 4.9.1.

 *

 * I converted all the pieces of the seed to a String before handing

 * it over to the MD5 hash so that you could print it out to make

 * sure it contains the data you expect to see and to give a nice

 * warm fuzzy.  If you need better performance, you may want to stick

 * to byte[] arrays.

 *

 * I believe that it is important that the algorithm for

 * generating random GUIDs be open for inspection and modification.

 * This class is free for all uses.

 *

 *

 * - Marc

 */



publicclassRandomGUIDextendsObject
{



   
public String valueBeforeMD5 ="";

   
public String valueAfterMD5 ="";

   
private
static Random myRand;

   
private
static SecureRandom mySecureRand;



   
private
static String s_id;



    /*

     * 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(booleansecure) {

        getRandomGUID(secure);

    }



    /*

     * Method to generate the random GUID

     */

   
private
void getRandomGUID(booleansecure) {

        MessageDigest md5 =
null;

        StringBuffer sbValueBeforeMD5 =
new StringBuffer();



       
try {

            md5 = MessageDigest.getInstance("MD5");

        }
catch (NoSuchAlgorithmException e) {

            System.out.println("Error: "+ e);

        }



       
try {

           
long time = System.currentTimeMillis();

           
long rand =
0;



           
if (secure) {

                rand = mySecureRand.nextLong();

            }
else {

                rand = myRand.nextLong();

            }



           
// This StringBuffer can be a long as you need; the MD5

           
// hash will always return 128 bits.  You can change

           
// the seed to include anything you want here.

           
// You could even stream a file through the MD5 making

           
// the odds of guessing it at least as great as that

           
// of guessing the contents of the file!

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

           
for (intj =0;
j < array.length; ++j) {

               
int b = array[j] &
0xFF;

               
if (b <
0x10) sb.append('0');

                sb.append(Integer.toHexString(b));

            }



            valueAfterMD5 = sb.toString();



        }
catch (Exception e) {

            System.out.println("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();

        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 (inti=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());

        }

    }
}
-----------------------------------------------------------------------------
importjava.security.*;



public
class RandomGUIDdemo {

    // Generate 20 of 'em!

    public
static void
main(String[] args) {

       for(inti=1;
i<=20; i++) {

       RandomGUID myguid =
new RandomGUID(false);

       System.out.println(i +
" " + myguid.toString());

     }

    }

生成唯一32位ID编码代码Java(GUID)的更多相关文章

  1. 生成随机32位Token43位asekey

    // 生成随机32位Token字符和43位AseKey var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', ' ...

  2. JAVA-产生唯一32位GUID

    import java.net.*; import java.util.*; import java.security.*; import org.apache.log4j.Logger; /** * ...

  3. 如何生成唯一的server Id,server_id为何不能重复?

    我们都知道MySQL用server-id来唯一的标识某个数据库实例,并在链式或双主复制结构中用它来避免sql语句的无限循环.这篇文章分享下我对server-id的理解,然后比较和权衡生成唯一serve ...

  4. 【JAVA】生成一个32位的随机数。防止重复,保留唯一性

    作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985, QQ986945193 微博:http://weibo.com/mcxiaobing import ...

  5. Java 生成16/32位 MD5

    http://blog.csdn.net/codeeer/article/details/30044831

  6. iOS生成一个32位的UUID

    - (NSString *)uuidString { CFUUIDRef uuid_ref = CFUUIDCreate(NULL); CFStringRef uuid_string_ref= CFU ...

  7. 在Delphi中获得唯一32位长字符串

    function GetGUID: string; var   vGUID: TGUID;   vTemp:string; begin   if S_OK = CreateGuid(vGUID) th ...

  8. java生成32位UUID

    java生成32位UUID,具体代码如下: package com.fxsen.uuid; import java.util.UUID; /** * Copyright: Copyright (c) ...

  9. 生成32位UUID及生成指定个数的UUID

    参考地址:https://blog.csdn.net/xinghuo0007/article/details/72868799 UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯 ...

随机推荐

  1. unity 播放外部视频

    摘要: Unity支持的播放视频格式有.mov..mpg..mpeg..mp4..avi和.asf.只需将对应的视频文件拖拽入Project视图即可,它会自动生成对应的MovieTexture对象. ...

  2. zoj 1109 zoj 1109 Language of FatMouse(字典树)

    好开心,手动自己按照字典树的思想用c写了一个优化后的trie字典树,就是用链表来代替26个大小的字符数组.完全按照自己按照自己的想法打的,没有参考如何被人的代码.调试了一天,居然最后错在一个小问题上, ...

  3. struts2+hibernate环境搭建

    使用的是myeclipse2014,搭建比较简单,很多jar包不用自己引入,很多初始配置文件不需要自己写.后面会介绍ssh的搭建. 首先新建web project. 1.右键项目,如图所示 这个直接f ...

  4. [Swust OJ 582]--放学了,抢机子了(SPFA)

    题目链接:http://acm.swust.edu.cn/problem/0582/ Time limit(ms): 5000 Memory limit(kb): 65535   Descriptio ...

  5. 在InteliJ IDEA中写Dart及配置IDEA - Dart Plugin

    此文运用的是优雅的Markdown而书 Dart官方建议使用的编译器是DartEditor,我下载下来看下,和Eclipse的界面很相像.对于Eclipse,我是既爱又恨,爱它的稳定,恨它的功能没有I ...

  6. A Byte of Python 笔记(2)基本概念:数、字符串、转义符、变量、标识符命名、数据类型、对象

    第4章 基本概念 字面意义上的常量 如5.1.23.9.23e-3,或者 'This is a string'."It's a string!" 字符串等 常量,不能改变它的值 数 ...

  7. poj 3358

    /** 大意: 给定小数(p/q),求其循环节的大小和循环节开始的位置 解法: 若出现循环 ai*2^m= aj%p; 即 2^m %p =1 若2与p 互素,则可由欧拉函数的, 不互素,需将其转化为 ...

  8. Linux串口编程详解(转)

    串口本身,标准和硬件 † 串口是计算机上的串行通讯的物理接口.计算机历史上,串口曾经被广泛用于连接计算机和终端设备和各种外部设备.虽然以太网接口和USB接口也是以一个串行流进行数据传送的,但是串口连接 ...

  9. FreeBSD 10安装KDE桌面环境简介(亲测bsdconfig命令有效)

    FreeBSD 10出来一段时间了,自己摸索装上KDE环境,网上介绍的都是10以前版本的,要么对现在的不合适,走了一大圈弯路还是装不好:要么太繁琐且装了一堆无用的软件.本着让更多人能快速方面的入门Fr ...

  10. centos 环境下monolog+php 方案

    1.在项目中,日志系统有多重要详细所有程序员都知道,monolog就是一个最好的解决方案,有各种级别,各种日志存储方式,具体可以上monolog官方了解http://monolog.ow2.org/ ...