|
|
 |
crypt (PHP 3, PHP 4, PHP 5) crypt -- Encripta una cadena mediante un algoritmo no reversible (hash) Descripciónstring crypt ( string cadena [, string semilla] )
crypt() encriptará una cadena utilizando el
método estándar de encriptación del Unix: DES.
Los argumentos son una cadena a encriptar y una cadena semilla
de 2 caracteres en la que basar la encriptación. Vea la página del
manual de Unix sobre crypt para más información.
Si el argumento de semilla no se proporciona, será generado
aleatoriamente por PHP cada vez que se llama a la función.
Algunos sistemas operativos soportan más de un tipo de encriptación.
De hecho, algunas veces la encriptación estándar DES es sustituÃda
por un algoritmo de encriptación basado en MD5. El tipo de
encriptación se selecciona en base al argumento semilla. En tiempo de
instalación, PHP determina la capacidad de la función de
encriptación y aceptará semillas para otros tipos de encriptación.
Si no se proporciona la semilla, PHP intentará generar una
semilla estándar DES de 2 caraceres por defecto, excepto si el
tipo de encriptación estándar del sistema es el MD5, en cuyo caso
se generará una semilla aleatoria compatible con MD5. PHP
fija una constante llamada CRYPT_SALT_LENGTH que le especifica si
su sistema soporta una semilla de 2 caracteres o si se debe usar
la semilla de 12 caracteres de longitud.
Si se utiliza la semilla proporcionada, debe tenerse en cuenta que la semilla
se genera una sola vez. Por tanto, si se llama a esta función repetidamente,
puede que se produzca un potencial problema de seguridad.
La función estándar de encriptación crypt() devuelve
la semilla como los dos primeros caracteres de la salida generada. Además, solamente
emplea los 8 primeros caracteres del parámetro cadena, por lo que
si se utilizan 2 cadenas largas cuyos 8 primeros caracteres son identicos, la salida generada será
la misma (siempre que se emplee la misma semilla).
En los sistemas en los que la función crypt() soporta múltiples
tipos de encriptación, las siguienes constantes son fijadas a
0 ó 1 dependiendo de si está disponible el tipo dado:
CRYPT_STD_DES - Encriptación DES estándar con semilla de 2 caracteres
CRYPT_EXT_DES - Encriptación DES extendida con semilla de 9 caracteres
CRYPT_MD5 - Encriptación MD5 con semilla de 12 caracteres y comenzando
por $1$
CRYPT_BLOWFISH - Encriptación DES extendida con semilla de 16 caracteres
y comenzando por $2$ o $2a$
Nota:
No existe una función de desencriptado, ya que crypt()
utiliza algoritmos no reversibles.
Ejemplo 1. Ejemplos de crypt() |
<?php
$contrasena = crypt('mi_contrasena'); if (crypt($datos_introducidos_por_el_usuario, $contrasena) == $contrasena) {
echo "La contrasena proporcionada por el usuario coincide con la contrasena establecida";
}
?>
|
|
Ejemplo 2. Empleando crypt() con htpasswd |
<?php
$contrasena = 'mi_contrasena';
$hash = crypt($contrasena);
?>
|
|
Ejemplo 3. Empleando crypt() con diferentes métodos de encriptación |
<?php
if (CRYPT_STD_DES == 1) {
echo 'DES estandar: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}
if (CRYPT_EXT_DES == 1) {
echo 'DES extendido: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}
if (CRYPT_MD5 == 1) {
echo 'MD5: ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}
if (CRYPT_BLOWFISH == 1) {
echo 'Blowfish: ' . crypt('rasmuslerdorf', '$2a$07$rasmuslerd...........$') . "\n";
}
?>
|
El resultado del ejemplo seria algo
similar a: DES estandar: rl.3StKT.4T8M
DES extendido: _J9..rasmBYk8r9AiWNc
MD5: $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish: $2a$07$rasmuslerd............nIdrcHdxcUxWomQX9j6kvERCFjTg7Ra |
|
Vea también: md5() y la extensión
Mcrypt.
solar at openwall dot com
23-Dec-2005 11:20
With different password hashing methods supported on different systems and with the need to generate salts with your own PHP code in order to use the more advanced / more secure methods, it takes special knowledge to use crypt() optimally, producing strong password hashes. Other message digest / hashing functions supported by PHP, such as md5() and sha1(), are really no good for password hashing if used naively, resulting in hashes which may be brute-forced at rates much higher than those possible for hashes produced by crypt().
I have implemented a PHP password hashing framework (in PHP, tested with all of PHP 3, 4, and 5) which hides the complexity from your PHP applications (no need for you to worry about salts, etc.), yet does things in almost the best way possible given the constraints of the available functions. The homepage for the framework is:
http://www.openwall.com/phpass/
I have placed this code in the public domain, so there are no copyrights or licensing restrictions to worry about.
P.S. I have 10 years of experience in password (in)security and I've developed several other password security tools and libraries. So most people can feel confident they're getting this done better by using my framework than they could have done it on their own.
hotdog (at) gmx (dot) net
16-Nov-2005 07:34
WRONG:
$mypassword = "toto";
$smd5_pass = "{SMD5}......." // in openldap
if (preg_match ("/{SMD5}/i", $smd5_pass))
{
$encrypted = substr($md5_pass, 6);
$hash = base64_decode($encrypted);
$salt = substr($hash,16);
$mhashed = mhash(MHASH_MD5, $mypassword . $salt) ;
$without_salt = explode($salt,$hash_hex);
if ($without_salt[0] == $mhashed) {
echo "Password verified <br>";
} else {
echo "Password Not verified<br>";
}
}
$without_salt = explode($salt,$hash_hex); should be $without_salt = explode($salt,$hash);
RIGHT:
$mypassword = "toto";
$smd5_pass = "{SMD5}......." // in openldap
if (preg_match ("/{SMD5}/i", $smd5_pass))
{
$encrypted = substr($md5_pass, 6);
$hash = base64_decode($encrypted);
$salt = substr($hash,16);
$mhashed = mhash(MHASH_MD5, $mypassword . $salt) ;
$without_salt = explode($salt,$hash);
if ($without_salt[0] == $mhashed) {
echo "Password verified <br>";
} else {
echo "Password Not verified<br>";
}
}
bjorninges dot spam at gmail dot com
06-Nov-2005 02:16
Note to topace's code: you should not use $_POST['password'] directly in your query as you are open to sql-injects.
Use the quote_smart() function from http://no.php.net/mysql_real_escape_string before adding user-submitted data to the query
topace at lightbox dot org
22-Sep-2005 09:34
To authenticate against a stored crypt in MySQL, simply use:
SELECT ................
AND Password=ENCRYPT('".$_POST['password']."',Password)
MagicalTux at FF dot st
15-Jun-2005 12:53
Since many of you are wondering why when providing salt the characters over the 8th are ignored in the password, I'll clarify it a bit.
By default, PHP will try to use the best encryption method available on your system : MD5 or Simple DES.
Usually this is the MD5 method ($1$).
In this case, the salt must look like : "$1$xxxxxxxx$" where x are random ASCII characters. When you use MD5 passwords, all characters of the password are encrypted in this 34 characters hash.
However if your salt starts with an ASCII character, the system will assume it's a standard DES encrypted password. The main weakness of this system : only the 8 first characters of the password are used.
A correct version of the code :
<?php
function makesalt($type=CRYPT_SALT_LENGTH) {
switch($type) {
case 8:
$saltlen=9; $saltprefix='$1$'; $saltsuffix='$'; break;
case 2:
default: $saltlen=2; $saltprefix=''; $saltsuffix=''; break;
}
$salt='';
while(strlen($salt)<$saltlen) $salt.=chr(rand(64,126));
return $saltprefix.$salt.$saltsuffix;
}
$salt=makesalt();
$longpassword='fez1c89ez1c98ez4c89z4eqf98ez';
$encrypted = crypt($longpassword, $salt);
$encrypted2 = crypt(substr($longpassword, 0, 8), $encrypted);
if ($encrypted == $encrypted2) {
echo 'Match: Weak encryption method (Standard DES)';
} else {
echo 'NoMatch: Strong encryption method (MD5)';
}
?>
If you use makesalt(2) you will force usage of Standard DES method, and the passwords will match. If you just use makesalt() there's great chances you'll have a MD5 password (don't know any system used nowadays which does not support MD5 passwords).
Finally, do not look at md5() PHP function if you want a md5 password, that's not related. UNIX MD5 passwords uses a salt, are 34 character long and start with $1$. The reply from md5() is 32 characters long, and is more adapted for file integrity check (call that a checksum).
Some people use sha1() passwords but without salt. Here's my simple sha1crypt function which will work with standard crypt passwords (by calling crypt()) AND a home-made "sha1" encryption method.
<?php
function sha1crypt($password, $salt=null) {
if ( (is_null($salt)) || (strlen($salt)<1) ) {
$salt='';
while(strlen($salt)<10) $salt.=chr(rand(64,126));
$salt='$sha1$'.$salt.'$';
}
if ($salt{0}!='$') return crypt($password, $salt);
$tmp=explode('$',$salt);
if ($tmp[1]!='sha1') return crypt($password, $salt);
$saltstr=$tmp[2];
if (strlen($saltstr) != 10) return crypt($password, $salt);
$encrypt=base64_encode(sha1($saltstr.$password,true));
return '$sha1$'.$saltstr.'$'.$encrypt;
}
$pass=sha1crypt('foobar');
echo $pass."\n";
echo sha1crypt('foobarbaz',$pass)."\n";
echo sha1crypt('foobar',$pass)."\n";
echo sha1crypt('foobar','$1$blahblahg$')."\n";
?>
will output:
$sha1$oFkYeI|vuu$d3n7D30OnecZSbS6KIbxCch608A=
$sha1$oFkYeI|vuu$iA8KmbCZun1G1gEw2qVr42ELVH4=
$sha1$oFkYeI|vuu$d3n7D30OnecZSbS6KIbxCch608A=
$1$blahblah$/8Hme91aEkHzLaVk0g9EQ0
My sha1-encrypted passwords are 45 characters long.
Remember to read that too before using SHA1 passwords too :
http://www.schneier.com/blog/archives/2005/02/sha1_broken.html
ceo at l-i-e dot com
06-Jun-2005 06:03
The people confused about the first 2 characters of the plain-text password being used as the salt are... confused.
AFTER you crypt() your plain-text password, with 2 RANDOM characters, the RESULTING scrambled output with have the 2 randomly-selected characters as its first 2 characters.
Later, to check a password presented by the user, you use the first 2 characters of the SCRAMBLED password as the salt.
So you do not need to remember the salt elsewhere -- it is buried in the encrypted output.
This is by design by very very very clever cryptologists, and in no way, shape, or form decreases the "security" of the algorithm.
The same is true of all the encryption algorithms here -- The salt may be 27 characters long, and embedded in the middle of the crypted string, but it's still there, and that's Good.
I hope this note decreases the confusion caused by the 2 early notes discussing salt.
Vlad Alexa Mancini mancin at nextcode dot org
15-May-2005 01:57
cleaner version of shadow() and with more ascii chars
<?php
function shadow ($input){
for ($n = 0; $n < 9; $n++){
$s .= chr(rand(64,126));
}
$seed = "$1$".$s."$";
$return = crypt($input,$seed);
return $return;
}
>
kevin at sylandroXgetridofthisbitX dot com
20-Apr-2005 12:55
Even worse, using the first two letters of the password as the salt removes the whole point of having salt in the first place, which is that without it, it's trivial to create a dictionary of passwords-to-encrypted-passwords. Without salt (or with using a salt directly derived from the password) there's only one possible encrypted password per password. With the two character salt, there's 4096, which makes the idea a lot less feasible.
19-Apr-2005 01:57
>icecube at fr dot fm 07-Mar-2002 09:53
>To generate a .htaccess-based authentication with DES,
>you have to use the first two characters of your password
>as salt.
This is a _really_ bad idea, seeing how the two first letters of your password will be reveiled, effectively reducing the quality of your password.
Your example assigns "sonH/h2hpGtHk" to $ht_pass, where "so" of course are the first to letters in something. Try it out for yourself. Switching the password to "icecube" gives "ickJ.ZxzjXpNE" as the output. Get my point?
The salt is always included in the encrypted string. Use a random salt instead.
postal2600 at yahoo dot com
16-Mar-2005 02:07
I'll take the example from above and take a situation that I've ecountered and show you something that puts this function in a dark shadow of insecurity:
<?php
$password = crypt('postal2600','CyberBoard');
if (crypt('postal26??', $password) == $password) {
echo "Password verified!";
}
?>
Instad of ?? you can put anything an see that allway the password will be verified. So i strongly recomand that the md5 function should be used instead.
kb at -NOSPAM-diggersdive dot info
30-Dec-2004 08:18
It is likely that the php version of crypt() interfaces relatively directly with the C-library crypt() function, usually contained in libcrypt.
Depending on your implementation and the default salt, you may or may not get the same crypt'd password out of eight characters as you would a longer string starting with those same eight characters.
See crypt(3) on your system for more documentation on how it works based on different encryption types.
genius at clan-aftershock dot com
28-Nov-2004 05:10
I discovered in the script stated before, when using a salt string the passwords length cannot be longer than 8 characters. However, when not using a salt string, it can exceded that limit.
Modified Example from athony, not using the salt.
<?php
$password = "qwertyuiopasdfghjkl";
$encrypted = crypt($password);
$shortPass = substr($password, 0, 8);
if (crypt( $shortPass, $encrypted ) == $encrypted )
echo "The passwords match";
else
echo "The passwords do not match";
?>
This will print: "The passwords do not match"
The check for password would still work if it was correct. Just by shortening the password string to eight, or extending the substr, or decalring the shortpass the same as the pass, it would be: "The passwords do match"
So the eight letter limit only works when using a salt.
antony at anonymous dot anon dot com
26-Nov-2004 08:21
There appears to be a limitation with this function, where it only validates upto a characters, therefore the 9th character onwards can be ommitted, which limits useful passwords to 8 characters only. Example
<?php
$password = "qwertyuiopasdfghjkl";
$salt = ""0f2d92cee71e5f93f3abecdc666a6b7d";
$salt = substr($salt, 0, CRYPT_SALT_LENGTH );
$encrypted = crypt($password, $salt);
// Now do the comparison
$shortPass = substr($password, 0, 8);
if (crypt( $shortPass, $encrypted ) == $encrypted )
echo "The passwords match";
else
echo "The passwords do not match";
?>
This will print: "The passwords match" even though $shortPass is "qwertyui" and $password is "qwertyuiopasdfghjkl"
thorhajo at gmail dot com
02-Sep-2004 03:34
Here's a little function I wrote to generate MD5 password hashes in the format they're found in /etc/shadow:
function shadow($password)
{
$hash = '';
for($i=0;$i<8;$i++)
{
$j = mt_rand(0,53);
if($j<26)$hash .= chr(rand(65,90));
else if($j<52)$hash .= chr(rand(97,122));
else if($j<53)$hash .= '.';
else $hash .= '/';
}
return crypt($password,'$1$'.$hash.'$');
}
I've written this so that each character in the a-zA-Z./ set has a 1/54 of a chance of being selected (26 + 26 + 2 = 54), thus being statistically even.
php at SPAM_tlarson dot com
25-Jun-2002 10:17
There's always been a bit of confusion as to what makes a good salt and what doesn't. Remember that it doesn't matter at all how easy a salt is to guess. No one ever HAS to guess the salt: it's already given.
The only only important consideration when generating a salt is to make sure that all salts are unique--that way the same password will be encrypted differently (i.e. the encrypted passwords will look different) for different users.
One of the simplest ways to generate a unique salt is to use some string that will be different every time the procedure is called. Here's a simple example:
<?php
$jumble = md5(time() . getmypid());
$salt = substr($jumble,0,$salt_length);
?>
Given a string consisting of the current time (in seconds) concatinated with the current process id, the string will never be the same twice, assuming that the function is never called more than once per second. Calculating the md5 sum over that string creates another string from which you can extract any substring and still end up with a unique sequence.
If you're going to be generating more than one password per second, just throw a rand($x,$y) in there to add a little more entropy.
| |
|
| Chiste de... Parejas | | Tierra trágame | - Oye Pepe, ¿sigues siendo novio de Pepita?
- No, ya no...
- Menos mal, que tía más impresentable, era fea, una niña mimada y además estaba loca. No la merecías.
- Ya, bueno, pues ahora es mi mujer. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|