生成唯一随机密钥的最简单方法

时间:2016-06-01 20:21:34

标签: php random key unique

问题不在于如何'生成这样一个密钥。有很多答案。有些像时间戳一样简单,但是其他一些东西并不像rand()中的一些字符那么独特。

我想知道的是,为什么不将两者结合起来? 如果我在几秒或几毫秒内取时间戳并在其间添加随机字符(但没有数字),那么会不会产生随机且唯一的字符串?

问题并不是针对一种编程语言,而是为了给你一些我用php编写的代码:

$token = (string) preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', microtime());
$l = strlen($token);
$c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for($i = 0; $i < $l; $i++){
    $token = substr_replace($token, $c[rand(0, 51)], rand(0, $l+$i), 0);
}

echo $ token;

我真的很期待一些随机性的答案!

谢谢;) 莱尼

1 个答案:

答案 0 :(得分:2)

我更喜欢生成GUID。这里有一些代码可以帮到你。

 function getGUID(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
            return $uuid;
        }
    }

        $GUID = getGUID();
        echo $GUID;

这是我的来源。 http://guid.us/GUID/PHP

相关问题