如何在php中生成一次6位数密码?

时间:2012-01-11 11:59:24

标签: php security cryptography

如何使用移动设备在PHP中生成一次性密码以进行双因素身份验证

5 个答案:

答案 0 :(得分:6)

试试这个:

<?php    
$pass= rand(100000, 999999);
?>

答案 1 :(得分:3)

<?php
function generatePassword($length, $strength) 
{
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) 
    {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength & 2) 
    {
        $vowels .= "AEUY";
    }
    if ($strength & 4) 
    {
        $consonants .= '23456789';
    }
    if ($strength & 8) 
    {
        $consonants .= '@#$%';
    }
    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) 
    {
        if ($alt == 1) 
        {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } 
        else 
        {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}


    echo generatePassword(6,4);
?>

答案 2 :(得分:0)

您可以使用类似md5或sha1的内容来执行此操作:

print substr(md5("text"), 0, 6);

如果它必须是唯一的,您可能想要检查存储已生成密码的数据库,或使用更长的密码,因为可以很快使用6位数。

你说数字,如果只是数字,你可以这样做:

print mt_rand(100000, 999999);

答案 3 :(得分:-2)

<?php
/*****
Returns a randomized string of chars/sybols/numbers for specified length
@param $l = length (default=8)
@param $s = use symbols? T/F
@param $a = use alpha characters? T/F
@param $n = use numbers? T/F
*****/
function random_chars($l=8,$s=1,$a=1,$n=1) {
  $string = ''; $chars = array();
  if ($s) $chars = array_merge($chars,array(
                     33,35,36,37,38,40,41,42,43,44,45,
                     46,47,58,59,60,61,62,63,64,91,93,
                     94,95,123,124,125,126
                     ));
  if ($a) $chars = array_merge($chars,array(
                     65,66,67,68,69,70,71,72,73,74,
                     75,76,77,78,79,80,81,82,83,84,
                     85,86,87,88,89,90,
                     97,98,99,100,101,102,103,104,105,106,
                     107,108,109,110,111,112,113,114,115,116,
                     117,118,119,120,121,122
                     ));
  if ($n) $chars = array_merge($chars,array(
                     48,49,50,51,52,53,54,55,56,57
                     ));
  for ($i=0;$i<$l;$i++) {shuffle($chars);$string.=chr(reset($chars));}
  return $string;
  }
?>

示例:

$password = random_chars(12); // 12-length alpha/numbers/symbols
$password = random_chars(12,0); // 12-length alpha/numbers
$password = random_chars(12,0,0); // 12-length numbers only

答案 4 :(得分:-2)

<?php

function random($length = 6)
{      
    $chars = 'bcdfghjklmnprstvwxzaeiou0123456789';
    $result = '';

    for ($p = 0; $p < $length; $p++)
    {
        $result .= ($p%2) ? $chars[mt_rand(19, 23)] : $chars[mt_rand(0, 18)];
    }

    return $result;
}
echo random();
?>