`

随机GUID

    博客分类:
  • Java
阅读更多
/*
Seeding String=joeyin/137.82.182.17:1152652666395:-2655885710548956891
rawGUID=ba6d3836cb5cd6f2e1bf66620cfc1b08
RandomGUID=BA6D3836-CB5C-D6F2-E1BF-66620CFC1B08
Seeding String=joeyin/137.82.182.17:1152652666395:8837199841642248984
rawGUID=55acedd65014369f2500e07fcaeb7c8c
RandomGUID=55ACEDD6-5014-369F-2500-E07FCAEB7C8C
Seeding String=joeyin/137.82.182.17:1152652666395:4210831876271338242
rawGUID=7a96375818c113c70fe74bb4fdba30de
RandomGUID=7A963758-18C1-13C7-0FE7-4BB4FDBA30DE
Seeding String=joeyin/137.82.182.17:1152652666395:-5617766000346159985
rawGUID=822dfcd0217938364415e5809fe46a91
RandomGUID=822DFCD0-2179-3836-4415-E5809FE46A91
Seeding String=joeyin/137.82.182.17:1152652666395:-7651391643447498604
rawGUID=19d58fd5c185b286a0a8f3f36f396ebb
RandomGUID=19D58FD5-C185-B286-A0A8-F3F36F396EBB
Seeding String=joeyin/137.82.182.17:1152652666395:-621723023330936579
rawGUID=feff7e4a8e3459d428ec55f3ffb04005
RandomGUID=FEFF7E4A-8E34-59D4-28EC-55F3FFB04005
*/
/*
 * 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
 *
 */

import java.net.*;
import java.util.*;
import java.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
 */

public class RandomGUID extends Object {


    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(boolean secure) {
        getRandomGUID(secure);
    }

    /*
     * Method to generate the random GUID
     */
    private void getRandomGUID(boolean secure) {
        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 (int j = 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 (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());
        }
    }
}
 
分享到:
评论

相关推荐

    Guid生成器(随机生成工具)

    Guid(Globally Unique Identifier)是一种在分布式网络环境中用于唯一标识对象的128位数字。它是微软.NET框架中广泛使用的标识符,特别是在数据库、编程和网络通信中。Guid生成器是一个工具,能够帮助用户快速生成...

    random-guid:生成随机 GUID

    randomString([字符串盐]) 生成随机字符串randomGuid([int numberOfBlocks, [int blockLength, [string salt]]]) 生成一个随机的 guid,用破折号分隔。用法var randomGuid = require("random-guid") .randomGuid;...

    生成随机码GUID,欢迎试用

    生成随机码GUID生成随机码GUID生成随机码GUID

    全能GUID生成工具

    用来生成随机GUID和顺序GUID,需要源码与我联系

    随机生成GUID

    标题“随机生成GUID”指的是使用C#编程语言编写的一段代码示例,其目的是演示如何生成具有唯一性的GUID值。 GUID由128位数字组成,通常以32个十六进制数字和4个破折号的格式表示。这些数字是通过算法计算得出的,...

    Guid随机生成器(工具)-下载

    Guid随机生成器是一款实用的小工具,它的主要功能是生成全局唯一的Guid并将其复制到剪贴板,方便用户在编写代码或者配置文件时快速粘贴使用。这种工具简化了开发人员手动创建Guid的过程,提高了工作效率。 Guid的...

    guid.zip_C# guid 算法_GUID 算法_guid 代码

    然而,`Guid`的生成算法可以分为多个版本,如V1到V5,每种版本在生成策略上略有不同,例如V1基于时间戳和MAC地址,V4完全随机,而V5基于命名空间和名称。 标签中的"c#_guid_算法 guid_算法 guid_代码"进一步强调了...

    Guid号生成器,可以生成32位Guid号

    由于其独特性和随机性,Guid通常用于生成数据库中的主键,或者作为网络服务中请求的唯一标识符。 本“Guid号生成器”程序(guidgen.exe)可以快速生成32位的Guid字符串,无需了解其复杂的生成原理。在实际应用中,...

    GUID生成器,源码

    8. **随机性和唯一性**: 虽然GUID看似随机,但它实际上是由特定算法生成的,确保了在全局范围内的唯一性,而非纯粹的随机性。 9. **用途**: GUID常用于数据库主键、软件注册码、网络通信中的唯一标识等场景。 10. ...

    自动生成GUID(原码)

    3. 第三段:16位,用于随机或伪随机数,确保同一时刻不同网络节点生成的GUID不同。 4. 第四段:16位,与第三段类似,也是随机或伪随机数,增加了唯一性。 5. 第五段:最后32位,同样为随机或伪随机数,确保在同一...

    有趣的真随机数抽取guid 双色球例子

    GUID的生成基于多种不可预测的因素,如时间戳、系统硬件信息等,因此可以视为一种伪随机数。尽管不是完全的真随机数,但在大多数实际应用中,其随机性足够用于抽奖或类似需求。 2. **生成GUID**:在.NET框架中,...

    Guid生成器(工具)

    1. **随机生成**: 工具会根据Guid生成算法,快速生成一个全新的、未被使用过的Guid。 2. **复制到剪贴板**: 用户可以直接点击按钮,将生成的Guid复制到剪贴板,方便粘贴到需要的地方。 3. **批量生成**: 对于需要...

    Guid生成器

    GUID 的总数达到了2^128(3.4×10^38)个,所以随机生成两个相同GUID的可能性非常小,但并不为0。所以,用于生成GUID的算法通常都加入了非随机的参数(如时间),以保证这种重复的情况不会发生。

    GUID生成器

    GUID 的总数达到了2^128(3.4×10^38)个,所以随机生成两个相同GUID的可能性非常小,但并不为0。GUID一词有时也专指微软对UUID标准的实现。 在理想情况下,任何计算机和计算机集群都不会生成两个相同的GUID。随机...

    sql语句大全 包括常有语句 新手必备

    这里的 `newid()` 是一个函数,返回一个新的随机 GUID(全局唯一标识符),这样可以确保每次执行该查询时,返回的结果都是随机的。适用于需要随机抽样的情况,如: - 抽样调查:从大量数据中随机抽取样本进行分析。...

    Guid和Int类型主键效率的比较

    这是因为Int类型的存储空间小,排序和索引效率高,而GUID类型的主键由于其长度较长且生成方式的随机性,可能导致数据页分裂,增加磁盘I/O操作,从而降低插入效率。 然而,选择哪种类型的主键还应考虑实际应用场景的...

    asp.net System.Guid ToString五种格式

    在.NET框架中,System.Guid表示一个...此代码段将生成一个随机GUID,并按照不同的格式输出,帮助理解每种格式输出的具体表现形式。在实际应用中,开发者可以根据需要选择最合适的格式化方法,以适应不同的场景和需求。

    安卓模拟器blue stacks的iemi地址和guid修改器

    在BlueStacks中,GUID可能与模拟器的实例或者用户账户关联,改变GUID可能会对特定应用的授权或同步产生影响。 要修改BlueStacks的IMEI和GUID,首先需要确保模拟器已完全关闭,以免在修改过程中出现数据冲突或错误。...

    关于数据库唯一性的说明

    - `NEWID()` 是一个生成随机GUID的函数,返回一个16字节的二进制数据,格式为 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx。例如: ```sql INSERT INTO myTable VALUES (NEWID(), 4); ``` 2. **NEWSEQUENTIALID()** ...

    如何生成guid

    Go语言使用`crypto/rand`和`encoding/hex`包生成一个随机的16字节(128位)的值,然后转换成字符串表示: ```go import ( "crypto/rand" "encoding/hex" ) guid := make([]byte, 16) _, err := rand.Read...

Global site tag (gtag.js) - Google Analytics