Skip to content

Instantly share code, notes, and snippets.

@felipelavinz
Created March 20, 2014 03:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipelavinz/9656913 to your computer and use it in GitHub Desktop.
Save felipelavinz/9656913 to your computer and use it in GitHub Desktop.
Generar cadenas semi-aleatorias con PHP
<?php
// cuántos bytes deseas generar?
$bytes = 32;
// obtener bytes semi-aleatorios
$rand = openssl_random_pseudo_bytes( $bytes );
// $rand = "óx3OM·¸Z ÅÀKŸÅ7 #õ˜cb4G8Â,7OPc";
// esta cadena puede tener caracteres de control o no representables
// transformar a hexadecimal para obtener solamente caracateres representables
$to_hex = bin2hex( $rand );
// $to_hex = "f378334f4db7b85aa0c511c04b9fc51d370923f5986362344738c22c374f5063";
// la cadena resultante tiene el doble de caracteres que la cantidad de bytes pseudo aleatorios
@chevereto
Copy link

function random_string($length) {
    switch(true) {
        case function_exists('mcrypt_create_iv') :
            $r = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
        break;
        case function_exists('openssl_random_pseudo_bytes') :
            $r = openssl_random_pseudo_bytes($length);
        break;
        case is_readable('/dev/urandom') : // deceze
            $r = file_get_contents('/dev/urandom', false, null, 0, $length);
        break;
        default :
            $i = 0;
            $r = '';
            while($i ++ < $length) {
                $r .= chr(mt_rand(0, 255));
            }
        break;
    }
    return substr(bin2hex($r), 0, $length);
}

@felipelavinz
Copy link
Author

@chevereto las alternativas que planteas se puede considerar cuando openssl_random_pseudo_bytes() no está disponible y no es posible instalarlo (la que recurre a mcrypt_create_iv() es particularmente interesante) pero al parecer son de menos calidad que la primera, ya que ésta incorpora aleatoriedad de varias fuentes, entre ellas /dev/urandom y varias más.

En los comentarios de http://www.eschrade.com/page/generating-secure-cross-site-request-forgery-tokens-csrf/ uno miembro del proyecto Zend Framework 2 indica justamente que para generar tokens anti-CSRF recurren primero a openssl_random_pseudo_bytes() luego a mcrypt_create_iv() y luego a mt_rand().

El código al que hace referencia está en https://github.com/zendframework/zf2/blob/master/library/Zend/Math/Rand.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment