Foros del Web » Programando para Internet » PHP »

Para los GENIOS, problema al logear con encriptacion SHA-1 de SMF

Estas en el tema de Para los GENIOS, problema al logear con encriptacion SHA-1 de SMF en el foro de PHP en Foros del Web. hola amigos estoy haciendo una web en la que quiero usar la misma BD de mi foro SMF, estoy usando el foro SMF 2.0 que ...
  #1 (permalink)  
Antiguo 16/07/2011, 21:17
 
Fecha de Ingreso: julio-2010
Mensajes: 90
Antigüedad: 13 años, 9 meses
Puntos: 0
Para los GENIOS, problema al logear con encriptacion SHA-1 de SMF

hola amigos estoy haciendo una web en la que quiero usar la misma BD de mi foro SMF, estoy usando el foro SMF 2.0 que por lo que he podido ver, para almacenar las contraseñas usa una encriptacion SHA-1 de usuario y password osea algo asi:

sha1($usuario.password);

mi problema es que no se como hacer un sistema de logeo y que de alguna forma la contraseña que incluyan en el campo password del formulario se compare con la de la base de datos que esta cifrada y sepa si es correcta o no, aquí les dejo el fichero de encriptacion o login de smf:

Código PHP:
Ver original
  1. <?php
  2.     // Figure out the password using SMF's encryption - if what they typed is right.
  3.     if (isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40)
  4.     {
  5.         // Needs upgrading?
  6.         if (strlen($user_settings['passwd']) != 40)
  7.         {
  8.             $context['login_errors'] = array($txt['login_hash_error']);
  9.             $context['disable_login_hashing'] = true;
  10.             unset($user_settings);
  11.             return;
  12.         }
  13.         // Challenge passed.
  14.         elseif ($_POST['hash_passwrd'] == sha1($user_settings['passwd'] . $sc))
  15.             $sha_passwd = $user_settings['passwd'];
  16.         else
  17.         {
  18.             // Don't allow this!
  19.             validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
  20.  
  21.             $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
  22.  
  23.             if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
  24.                 redirectexit('action=reminder');
  25.             else
  26.             {
  27.                 log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
  28.  
  29.                 $context['disable_login_hashing'] = true;
  30.                 $context['login_errors'] = array($txt['incorrect_password']);
  31.                 unset($user_settings);
  32.                 return;
  33.             }
  34.         }
  35.     }
  36.     else
  37.         $sha_passwd = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  38.  
  39.     // Bad password!  Thought you could fool the database?!
  40.     if ($user_settings['passwd'] != $sha_passwd)
  41.     {
  42.         // Let's be cautious, no hacking please. thanx.
  43.         validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
  44.  
  45.         // Maybe we were too hasty... let's try some other authentication methods.
  46.         $other_passwords = array();
  47.  
  48.         // None of the below cases will be used most of the time (because the salt is normally set.)
  49.         if ($user_settings['password_salt'] == '')
  50.         {
  51.             // YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x, IkonBoard, and none at all.
  52.             $other_passwords[] = crypt($_POST['passwrd'], substr($_POST['passwrd'], 0, 2));
  53.             $other_passwords[] = crypt($_POST['passwrd'], substr($user_settings['passwd'], 0, 2));
  54.             $other_passwords[] = md5($_POST['passwrd']);
  55.             $other_passwords[] = sha1($_POST['passwrd']);
  56.             $other_passwords[] = md5_hmac($_POST['passwrd'], strtolower($user_settings['member_name']));
  57.             $other_passwords[] = md5($_POST['passwrd'] . strtolower($user_settings['member_name']));
  58.             $other_passwords[] = md5(md5($_POST['passwrd']));
  59.             $other_passwords[] = $_POST['passwrd'];
  60.  
  61.             // This one is a strange one... MyPHP, crypt() on the MD5 hash.
  62.             $other_passwords[] = crypt(md5($_POST['passwrd']), md5($_POST['passwrd']));
  63.  
  64.             // Snitz style - SHA-256.  Technically, this is a downgrade, but most PHP configurations don't support sha256 anyway.
  65.             if (strlen($user_settings['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256'))
  66.                 $other_passwords[] = bin2hex(mhash(MHASH_SHA256, $_POST['passwrd']));
  67.  
  68.             // phpBB3 users new hashing.  We now support it as well ;).
  69.             $other_passwords[] = phpBB3_password_check($_POST['passwrd'], $user_settings['passwd']);
  70.  
  71.             // APBoard 2 Login Method.
  72.             $other_passwords[] = md5(crypt($_POST['passwrd'], 'CRYPT_MD5'));
  73.         }
  74.         // The hash should be 40 if it's SHA-1, so we're safe with more here too.
  75.         elseif (strlen($user_settings['passwd']) == 32)
  76.         {
  77.             // vBulletin 3 style hashing?  Let's welcome them with open arms \o/.
  78.             $other_passwords[] = md5(md5($_POST['passwrd']) . $user_settings['password_salt']);
  79.  
  80.             // Hmm.. p'raps it's Invision 2 style?
  81.             $other_passwords[] = md5(md5($user_settings['password_salt']) . md5($_POST['passwrd']));
  82.  
  83.             // Some common md5 ones.
  84.             $other_passwords[] = md5($user_settings['password_salt'] . $_POST['passwrd']);
  85.             $other_passwords[] = md5($_POST['passwrd'] . $user_settings['password_salt']);
  86.         }
  87.         elseif (strlen($user_settings['passwd']) == 40)
  88.         {
  89.             // Maybe they are using a hash from before the password fix.
  90.             $other_passwords[] = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  91.  
  92.             // BurningBoard3 style of hashing.
  93.             $other_passwords[] = sha1($user_settings['password_salt'] . sha1($user_settings['password_salt'] . sha1($_POST['passwrd'])));
  94.  
  95.             // Perhaps we converted to UTF-8 and have a valid password being hashed differently.
  96.             if ($context['character_set'] == 'utf8' && !empty($modSettings['previousCharacterSet']) && $modSettings['previousCharacterSet'] != 'utf8')
  97.             {
  98.                 // Try iconv first, for no particular reason.
  99.                 if (function_exists('iconv'))
  100.                     $other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', $modSettings['previousCharacterSet'], $user_settings['member_name'])) . un_htmlspecialchars(iconv('UTF-8', $modSettings['previousCharacterSet'], $_POST['passwrd'])));
  101.  
  102.                 // Say it aint so, iconv failed!
  103.                 if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding'))
  104.                     $other_passwords[] = sha1(strtolower(mb_convert_encoding($user_settings['member_name'], 'UTF-8', $modSettings['previousCharacterSet'])) . un_htmlspecialchars(mb_convert_encoding($_POST['passwrd'], 'UTF-8', $modSettings['previousCharacterSet'])));
  105.             }
  106.         }
  107.  
  108.         // SMF's sha1 function can give a funny result on Linux (Not our fault!). If we've now got the real one let the old one be valid!
  109.         if (strpos(strtolower(PHP_OS), 'win') !== 0)
  110.         {
  111.             require_once($sourcedir . '/Subs-Compat.php');
  112.             $other_passwords[] = sha1_smf(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
  113.         }
  114.  
  115.         // Whichever encryption it was using, let's make it use SMF's now ;).
  116.         if (in_array($user_settings['passwd'], $other_passwords))
  117.         {
  118.             $user_settings['passwd'] = $sha_passwd;
  119.             $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  120.  
  121.             // Update the password and set up the hash.
  122.             updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt'], 'passwd_flood' => ''));
  123.         }
  124.         // Okay, they for sure didn't enter the password!
  125.         else
  126.         {
  127.             // They've messed up again - keep a count to see if they need a hand.
  128.             $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
  129.  
  130.             // Hmm... don't remember it, do you?  Here, try the password reminder ;).
  131.             if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
  132.                 redirectexit('action=reminder');
  133.             // We'll give you another chance...
  134.             else
  135.             {
  136.                 // Log an error so we know that it didn't go well in the error log.
  137.                 log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
  138.  
  139.                 $context['login_errors'] = array($txt['incorrect_password']);
  140.                 return;
  141.             }
  142.         }
  143.     }
  144.     elseif (!empty($user_settings['passwd_flood']))
  145.     {
  146.         // Let's be sure they weren't a little hacker.
  147.         validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood'], true);
  148.  
  149.         // If we got here then we can reset the flood counter.
  150.         updateMemberData($user_settings['id_member'], array('passwd_flood' => ''));
  151.     }
  152.  
  153.     // Correct password, but they've got no salt; fix it!
  154.     if ($user_settings['password_salt'] == '')
  155.     {
  156.         $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
  157.         updateMemberData($user_settings['id_member'], array('password_salt' => $user_settings['password_salt']));
  158.     }
  159.  
  160.     // Check their activation status.
  161.     if (!checkActivation())
  162.         return;
  163.  
  164.     DoLogin();
  165. }
  166.  
  167. function checkActivation()
  168. {
  169.     global $context, $txt, $scripturl, $user_settings, $modSettings;
  170.  
  171.     if (!isset($context['login_errors']))
  172.         $context['login_errors'] = array();
  173.  
  174.     // What is the true activation status of this account?
  175.     $activation_status = $user_settings['is_activated'] > 10 ? $user_settings['is_activated'] - 10 : $user_settings['is_activated'];
  176.  
  177.     // Check if the account is activated - COPPA first...
  178.     if ($activation_status == 5)
  179.     {
  180.         $context['login_errors'][] = $txt['coppa_no_concent'] . ' <a href="' . $scripturl . '?action=coppa;member=' . $user_settings['id_member'] . '">' . $txt['coppa_need_more_details'] . '</a>';
  181.         return false;
  182.     }
  183.     // Awaiting approval still?
  184.     elseif ($activation_status == 3)
  185.         fatal_lang_error('still_awaiting_approval', 'user');
  186.     // Awaiting deletion, changed their mind?
  187.     elseif ($activation_status == 4)
  188.     {
  189.         if (isset($_REQUEST['undelete']))
  190.         {
  191.             updateMemberData($user_settings['id_member'], array('is_activated' => 1));
  192.             updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > 0 ? $modSettings['unapprovedMembers'] - 1 : 0)));
  193.         }
  194.         else
  195.         {
  196.             $context['disable_login_hashing'] = true;
  197.             $context['login_errors'][] = $txt['awaiting_delete_account'];
  198.             $context['login_show_undelete'] = true;
  199.             return false;
  200.         }
  201.     }
  #2 (permalink)  
Antiguo 16/07/2011, 21:23
Avatar de jatg  
Fecha de Ingreso: abril-2011
Ubicación: caracas
Mensajes: 152
Antigüedad: 13 años
Puntos: 15
Respuesta: Para los GENIOS, problema al logear con encriptacion SHA-1 de SMF

hola extreme, trata de utilizar algo como esto si quieres te paso los archivos suerte


Código PHP:
Ver original
  1. if($_POST['username']!='' && $_POST['password']!='' && $_POST['password']==$_POST['password_confirmed'] && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && checkUnique('Username', $_POST['username'])==TRUE && checkUnique('Email', $_POST['email'])==TRUE)
  2.  
  3.  
  4.             $query = mysql_query("INSERT INTO users (`Username` , `Password`, `Email`, `Random_key`) VALUES ('".mysql_real_escape_string($_POST['username'])."', '".mysql_real_escape_string(md5($_POST['password']))."', '".mysql_real_escape_string($_POST['email'])."', '".random_string('alnum', 32)."')") or die(mysql_error());
  5.  
  6.             $getUser = mysql_query("SELECT ID, Username, Email, Random_key FROM users WHERE Username = '".mysql_real_escape_string($_POST['username'])."'") or die(mysql_error());
  7.  
  8.             if(mysql_num_rows($getUser)==1)
  9.             {
  10.  
  11.                 $row = mysql_fetch_assoc($getUser);
  12.                 $headers = 'From: [email protected]' . "\r\n" .
  13.                 'Reply-To: [email protected]' . "\r\n" .
  14.                 'X-Mailer: PHP/' . phpversion();
  15.                  $subject = "Activation de registro de usuarios www.josealexis.com";
  16.                  $message = "hola ".$row['Username'].", éste es su eslabón de activación para unir nuestro website. Para por favor confirmar su número de miembros haga clic en lo siguiente eslabón : http://www.josealexis.tk/confirm.php?ID=".$row['ID']."&amp;key=".$row['Random_key']. " gracias por registrarse";
  17.                  if(mail($row['Email'], $subject, $message, $headers))
  18.                 {//we show the good guy only in one case and the bad one for the rest.
  19.                     $msg = 'Registro creado. Por favor haga click en el enlace que le hemos enviado a su dirrecion de correo electronico para activar su cuenta.';
  20.                       echo "&msg=$msg";
  21.  
  22.  
  23.  
  24.  
  25.                 echo "&estatus=ok&"; //registro exitoso
  26.  
  27.                 }
  28.                 else {
  29.                     $error = 'La cuenta esta creada pero falta que usted active la misma en en link que le hemos enviado a su direccion de e-mail';
  30.                    echo "&error=". $error;
  31.                 }
  32.             }
  33.             else {
  34.                 $error = 'se ha terminado su tiempo de velides para activar su cuenta. Por favor registrese nuevamente .';
  35.                   echo "&error=". $error;
  36.             }
  37.  
  38.         }
  39.  
  40.          }
  41. ?>
  42. <?=$_SERVER['PHP_SELF']?>



aqui en confirm.php

Código PHP:
Ver original
  1. <?php
  2. require_once('db.php');
  3. include('functions.php');
  4.  
  5.     if($_GET['ID']!='' && numeric($_GET['ID'])==TRUE && strlen($_GET['key'])==32 && alpha_numeric($_GET['key'])==TRUE)
  6.     {
  7.  
  8.         $query = mysql_query("SELECT ID, Random_key, Active FROM users WHERE ID = '".mysql_real_escape_string($_GET['ID'])."'");
  9.  
  10.         if(mysql_num_rows($query)==1)
  11.         {
  12.             $row = mysql_fetch_assoc($query);
  13.             if($row['Active']==1)
  14.             {
  15.                 echo "&error=".$error = 'This member is already active !';
  16.             }
  17.             elseif($row['Random_key']!=$_GET['key'])
  18.             {
  19.                 echo "&error=".$error = 'The confirmation key that was generated for this member does not match with the one entered !';
  20.             }
  21.             else
  22.             {
  23.                 $update = mysql_query("UPDATE users SET Active=1 WHERE ID='".mysql_real_escape_string($row['ID'])."'") or die(mysql_error());
  24.                 $msg = 'Congratulations !  You just confirmed your membership !';
  25.             }
  26.         }
  27.         else {
  28.  
  29.             echo "&error=".$error = 'User not found !';
  30.  
  31.         }
  32.  
  33.     }
  34.     else {
  35.  
  36.         $error = 'Invalid data provided !';
  37.  
  38.     }
  39.  
  40.     if(isset($error))
  41.     {
  42.         echo "&error=".$error;
  43.     }
  44.     else {
  45.         echo "&msg=".$msg;
  46.     }
  47. ?>


y aqui el confirm_pass.php

Código PHP:
Ver original
  1. <?php
  2. require_once('db.php');
  3. include('functions.php');
  4.  
  5.     $query = mysql_query("SELECT * FROM users WHERE ID = '".mysql_real_escape_string($_GET['ID'])."'");
  6.  
  7.     if(mysql_num_rows($query)==1)
  8.     {
  9.         $row = mysql_fetch_assoc($query);
  10.         if($row['Temp_pass']==$_GET['new'] && $row['Temp_pass_active']==1)
  11.         {
  12.             $update = mysql_query("UPDATE users SET Pass = '".md5(mysql_real_escape_string($_GET['new']))."', Temp_pass_active=0 WHERE ID = '".mysql_real_escape_string($_GET['ID'])."'");
  13.             $msg = 'Your new password has been confirmed. You may login using it.';
  14.         }
  15.         else
  16.         {
  17.             $error = 'The new password is already confirmed or is incorrect';
  18.         }
  19.     }
  20.     else {
  21.         $error = 'You are trying to confirm a new password for an unexisting member';
  22.     }
  23.  
  24.     if(isset($error))
  25.     {
  26.         echo $error;
  27.     }
  28.     else {
  29.         echo $msg;
  30.     }
  31. ?>
__________________
www.josealexis.net
  #3 (permalink)  
Antiguo 16/07/2011, 21:27
Avatar de Sourcegeek
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: $mex['B.C.'];
Mensajes: 1.816
Antigüedad: 15 años
Puntos: 322
Respuesta: Para los GENIOS, problema al logear con encriptacion SHA-1 de SMF

Para ello tienes que encriptar la contraseña introducida en el formulario para comparar las dos encriptadas, y listo
__________________
Buscas desarrollador web? Sourcegeek. Diseño web, Maquetación y Programación
¡Escribe bien! Esto es un foro, no un Facebook para que escribas con los pies
  #4 (permalink)  
Antiguo 17/07/2011, 10:56
Avatar de Gurrutello  
Fecha de Ingreso: enero-2002
Ubicación: Ontario,Toronto [Canada]
Mensajes: 2.017
Antigüedad: 22 años, 3 meses
Puntos: 6
Respuesta: Para los GENIOS, problema al logear con encriptacion SHA-1 de SMF

Hola nunca he utizado SMF por lo que no se el tipo de conexiones o como se conecta a una base de datos

lo mas facil seria...
Ya que conoces que los passwords son asi..

sha1($usuario.$password);

Simplemente puedes hacer
// recoge variable y la pones en lowercase si es necesario

$username = strtolower(mysql_real_escape_string($_POST['username']));

$clave = sha1($_POST['username'].$_POST['password']; // comprobar que no esta lowercase, uppercase etc...

$query = mysql_query("SELECT username,password,ID FROM users WHERE LOWER(username) = '".$username."' LIMIT 1");

if(mysql_num_rows($query)==0){
echo 'usuario no encontrado';
}else{
// existe el nombre de usuario podemos hacer la comprobacion
while($row = mysql_fetch_assoc($query){
if($row['password']==$clave){
echo 'Usuario Existe';
}else{
echo 'Usuario NO Existe';
}
}
}

espero que te sirva
Saludos
__________________
Un Saludo
www.tutores.org
Asp | Php | Javascript | Perl | Coldfusion | Flash | +- 2000 codigos

Etiquetas: encriptacion, genios, html, sha-1, smf, formulario, usuarios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 11:02.