protected static function _digestOpenssl($algorithm, $data, $binaryOutput) { if ($algorithm == 'ripemd160') { $algorithm = 'rmd160'; } return openssl_digest($data, $algorithm, $binaryOutput); }
function makeHash($data, $alg) { // $s = hash_hmac('sha256', $data, 'secret', true); // return base64_encode($s); $ret = openssl_digest($data, $alg); return $ret; }
/** * @param string $data * @param string $algorithm * * @return Hash */ public static function digest(string $data, string $algorithm) : Hash { $hash = new Hash(); $hash->setAlgorithm($algorithm); $hash->setValue(openssl_digest($data, $algorithm, TRUE)); return $hash; }
private function compute($data) { switch ($this->getFavorite()) { case 'openssl': return sprintf('%s-%s', $this->type, base64_encode(openssl_digest($data, $this->type, true))); case 'hash': return sprintf('%s-%s', $this->type, base64_encode(hash($this->type, $data, true))); } throw new \RuntimeException('No hash function on this platform'); }
public function alta_tutor_inAction() { $request = $this->getRequest(); $session = $request->getSession(); $dni = $request->request->get('dni'); $Miusuario = $this->getDoctrine()->getRepository('tutoriasBundle:Persona')->findOneByDni($dni); $cant = sizeof($Miusuario); if ($cant == 0) { if ($this->VerificoPerfil('alta_tutor')) { $persona = new Persona(); $nombre = $request->request->get('nombre'); $apellido = $request->request->get('apellido'); $legajo = $request->request->get('legajo'); $email = $request->request->get('email'); $persona->setNombre($nombre); $persona->setApellido($apellido); $persona->setLegajo($legajo); $persona->setEmail($email); $persona->setActivo(1); $password = $request->request->get('password'); $em = $this->getDoctrine()->getManager(); $salCodifided = openssl_random_pseudo_bytes(32); //$sal = (string)$sal; //$sal =rand(5, 15); $sal = utf8_encode($salCodifided); $hash = openssl_digest($password . $sal, 'sha512'); $dni = $request->request->get('dni'); $perfil = $this->getDoctrine()->getRepository("tutoriasBundle:Perfil")->findOneBydescripcion('Tutor'); $persona->setIdperfil($perfil->getIdperfil()); $persona->setDni($dni); $persona->setSal($sal); $persona->setHash($hash); $em->persist($persona); $em->flush(); $tutor = new Tutor(); $tutor->setIdpersona($persona->getIdpersona()); $em->persist($tutor); $em->flush(); $session->set('mensaje_session', 'Alta de Tutor Exitosa!'); //return $this->redirectToRoute('tutorias_alta_tutor', array('usuario'=>$session->get('Usuario'),'estado'=>'ok','perfil'=>$session->get('perfil'),'tipo'=>$session->get('tipo')), 301); return $this->redirectToRoute('tutorias_show_tutor'); } else { return $this->redirectToRoute('tutorias_login', array('mensaje' => '', 'tipo' => ''), 301); } } else { #en el caso de que ya exista el usuario con ese DNi se redirige $mensaje = "Ya existe un usuario con el mismo DNI ,por favor ingrese los datos nuevamente"; return $this->alta_tutor($mensaje); } }
function podlove_handle_media_file_tracking(\Podlove\Model\MediaFile $media_file) { if (\Podlove\get_setting('tracking', 'mode') !== "ptm_analytics") { return; } if (strtoupper($_SERVER['REQUEST_METHOD']) === 'HEAD') { return; } $intent = new Model\DownloadIntent(); $intent->media_file_id = $media_file->id; $intent->accessed_at = date('Y-m-d H:i:s'); $ptm_source = trim(podlove_get_query_var('ptm_source')); $ptm_context = trim(podlove_get_query_var('ptm_context')); if ($ptm_source) { $intent->source = $ptm_source; } if ($ptm_context) { $intent->context = $ptm_context; } // set user agent $ua_string = trim($_SERVER['HTTP_USER_AGENT']); if ($agent = Model\UserAgent::find_or_create_by_uastring($ua_string)) { $intent->user_agent_id = $agent->id; } // save HTTP range header // @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 for spec if (isset($_SERVER['HTTP_RANGE'])) { $intent->httprange = $_SERVER['HTTP_RANGE']; } // get ip, but don't store it $ip_string = $_SERVER['REMOTE_ADDR']; try { $ip = IP\Address::factory($_SERVER['REMOTE_ADDR']); if (method_exists($ip, 'as_IPv6_address')) { $ip = $ip->as_IPv6_address(); } $ip_string = $ip->format(IP\Address::FORMAT_COMPACT); } catch (\InvalidArgumentException $e) { \Podlove\Log::get()->addWarning('Could not use IP "' . $_SERVER['REMOTE_ADDR'] . '"' . $e->getMessage()); } // Generate a hash from IP address and UserAgent so we can identify // identical requests without storing an IP address. if (function_exists('openssl_digest')) { $intent->request_id = openssl_digest($ip_string . $ua_string, 'sha256'); } else { $intent->request_id = sha1($ip_string . $ua_string); } $intent = $intent->add_geo_data($ip_string); $intent->save(); }
/** * Encrypt data using AES-256-CBC and the key provided as a parameter. * * @param string $data The data to encrypt. * @param string $secret The secret to use to encrypt the data. * * @return string The IV and encrypted data concatenated. * @throws \InvalidArgumentException If $data is not a string. * @throws \SimpleSAML_Error_Exception If the openssl module is not loaded. * * @see \SimpleSAML\Utils\Crypto::aesEncrypt() */ private static function _aesEncrypt($data, $secret) { if (!is_string($data)) { throw new \InvalidArgumentException('Input parameter "$data" must be a string.'); } if (!function_exists("openssl_encrypt")) { throw new \SimpleSAML_Error_Exception('The openssl PHP module is not loaded.'); } $raw = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true; $key = openssl_digest($secret, 'sha256'); $method = 'AES-256-CBC'; $ivSize = 16; $iv = substr($key, 0, $ivSize); return $iv . openssl_encrypt($data, $method, $key, $raw, $iv); }
public function verify_message($id = '', $data = '') { if ($id == '') { return 0; } $q = $this->db->query("SELECT `size`, `hlen`, `digest`, `bodydigest`,`attachments` FROM " . TABLE_META . " WHERE piler_id=?", array($id)); $digest = $q->row['digest']; $bodydigest = $q->row['bodydigest']; $size = $q->row['size']; $hlen = $q->row['hlen']; $attachments = $q->row['attachments']; $_digest = openssl_digest($data, "SHA256"); $_bodydigest = openssl_digest(substr($data, $hlen), "SHA256"); if ($_digest == $digest && $_bodydigest == $bodydigest) { return 1; } return 0; }
public function alta_tutor_inAction() { $request = $this->getRequest(); $session = $request->getSession(); $dni = $request->request->get('dni'); $Miusuario = $this->getDoctrine()->getRepository('tutoriasBundle:Persona')->findOneByDni($dni); if ($Miusuario = '') { if ($this->VerificoPerfil('alta_tutor')) { $persona = new Persona(); $nombre = $request->request->get('nombre'); $apellido = $request->request->get('apellido'); $legajo = $request->request->get('legajo'); $email = $request->request->get('email'); $persona->setNombre($nombre); $persona->setApellido($apellido); $persona->setLegajo($legajo); $persona->setEmail($email); $persona->setActivo(1); $password = $request->request->get('password'); $em = $this->getDoctrine()->getManager(); $salCodifided = openssl_random_pseudo_bytes(32); //$sal = (string)$sal; //$sal =rand(5, 15); $sal = utf8_encode($salCodifided); $hash = openssl_digest($password . $sal, 'sha512'); $dni = $request->request->get('dni'); $perfil = $this->getDoctrine()->getRepository("tutoriasBundle:Perfil")->findOneBydescripcion('Tutor'); $persona->setIdperfil($perfil->getIdperfil()); $persona->setDni($dni); $persona->setSal($sal); $persona->setHash($hash); $em->persist($persona); $em->flush(); $tutor = new Tutor(); $tutor->setIdpersona($persona->getIdpersona()); $em->persist($tutor); $em->flush(); return $this->redirectToRoute('tutorias_alta_tutor', array('usuario' => $session->get('Usuario'), 'estado' => 'ok', 'perfil' => $session->get('perfil'), 'tipo' => $session->get('tipo')), 301); } else { return $this->redirectToRoute('tutorias_alta_tutor', array('usuario' => $session->get('Usuario'), 'estado' => 'ok', 'perfil' => $session->get('perfil'), 'tipo' => $session->get('tipo'), 'result' => $result), 301); } } }
$dataBase = new dataBase(); if (isset($_POST["changeInfo"])) { $newEmail = $_POST["email"]; $id = $_POST["id"]; if ($_POST["email"] != "" && $_FILES["profilePicture"]["name"] != "") { if ($_FILES["profilePicture"]["type"] == "image/png" || $_FILES["profilePicture"]["type"] == "image/jpeg" || $_FILES["profilePicture"]["type"] == "image/gif") { if ($_FILES["profilePicture"]["size"] <= 2000000) { $newPictureName = newName($_FILES["profilePicture"]["name"]); while (file_exists("img\\" . $newPictureName)) { $newPictureName = newName($_FILES["profilePicture"]["name"]); } move_uploaded_file($_FILES['profilePicture']['tmp_name'], "img\\" . $newPictureName); $test = $dataBase->update("users", "email", "'" . $newEmail . "'", "profile_picture", "'" . $newPictureName . "'", "id", "'" . $id . "'"); $salt = $dataBase->getRow("salt", "users", true, "'" . $id . "'", "id"); $actualSalt = $salt[0]["salt"]; $hash = openssl_digest($newEmail . $actualSalt, 'sha512'); var_dump($test); setcookie("login", $newEmail . "," . $hash, time() + 2592000); header("location: gegevens-wijzigen-form.php"); } else { $_SESSION["notifications"]["type"] = "error"; $_SESSION["notifications"]["message"] = "File is too big"; header("location: gegevens-wijzigen-form.php"); } } else { $_SESSION["notifications"]["type"] = "error"; $_SESSION["notifications"]["message"] = "File is wrong type"; header("location: gegevens-wijzigen-form.php"); } } else { $_SESSION["notifications"]["type"] = "error";
/** * Returns a RIPDEMD160 hash of a value. * * @param string $data * * @return string */ public static function ripe160($data, $binary = false) { return openssl_digest($data, 'ripemd160', $binary); }
$checkPasswordQuery = ' SELECT hashed_password, salt FROM users WHERE email = :email '; $checkPasswordStatement = $db->prepare($checkPasswordQuery); $checkPasswordStatement->bindValue(':email', $email); $checkPasswordStatement->execute(); $passwordSaltedArray = array(); while ($row = $checkPasswordStatement->fetch(PDO::FETCH_ASSOC)) { $passwordSaltedArray[] = $row; } $passwordToCheck = openssl_digest($password . $passwordSaltedArray[0]['salt'], 'sha512'); $originalPassword = $passwordSaltedArray[0]['hashed_password']; if ($passwordToCheck == $originalPassword) { unset($_SESSION['login']); //hash the email + password that is salted with name 'salt' $hashedEmailSalt = openssl_digest($email . $passwordSaltedArray[0]['salt'], 'sha512'); setcookie('login', $email . ',' . $hashedEmailSalt, time() + 2592000); //30days setcookie('email', $email, time() + 2592000); header('location: dashboard.php'); } else { $_SESSION['message']['type'] = 'error'; $_SESSION['message']['text'] = 'password is wrong'; header('location: login-form.php'); } } } catch (PDOException $e) { $messageContainer = 'ERROR ERROR ERROR: ' . $e; } } ?>
<?php require "tt_config.php"; $conn = mysql_connect($myserver_name, $myserver_username, $myserver_password); if (!$conn) { die('Could not connect: ' . mysql_error()); } mysql_select_db($myserver_database, $conn); #$strsql="select * from `tb_todolist`"; $filename = "./add_user.json"; $handle = fopen($filename, "r"); $content = fread($handle, filesize($filename)); #print $content; $useradd = json_decode($content); print $useradd->{'user_name'}; print $useradd->{'user_passwd'}; $sqlstr = "INSERT INTO tb_user (user_name,user_passwd) VALUES (" . "'" . $useradd->{'user_name'} . "'" . ',' . "'" . openssl_digest($useradd->{'user_passwd'}, 'sha512') . "'" . ")"; echo $sqlstr; mysql_query($sqlstr); mysql_error(); mysql_close($conn);
if (isset($_COOKIE["login"])) { $userInformation = explode(',', $_COOKIE["login"]); $email = $userInformation[0]; $cookieString = $userInformation[1]; $validationComplete = false; $db = new PDO('mysql:host=localhost;dbname=opdracht_file_upload', 'root', 'root'); $cookieCheck = "SELECT salt from users where email = :email"; $cookieCheckStatement = $db->prepare($cookieCheck); $cookieCheckStatement->bindParam(":email", $userInformation[0]); $cookieCheckStatement->execute(); $saltAr = array(); while ($row = $cookieCheckStatement->fetch(PDO::FETCH_ASSOC)) { $saltAr[] = $row; } $salt = $saltAr[0]["salt"]; $toCheckCookieString = openssl_digest($email . $salt, 'sha512'); if ($toCheckCookieString == $cookieString) { $validationComplete = true; } else { setcookie("login", null, -1); $_SESSION["notifications"]["type"] = "error"; $_SESSION["notifications"]["message"] = "Something went wrong with your validation, please contact the webmaster"; } } else { $_SESSION["notifications"]["type"] = "error"; $_SESSION["notifications"]["message"] = "You are not logged in yet, please do"; header("location: login-form.php"); } if (isset($_GET["logout"])) { setcookie("login", null, -1); $_SESSION["notifications"]["type"] = "notifications";
<?php // session utils include 'sessions.php'; // open connection to the database include 'config.php'; include 'readDB.php'; include 'writeDB.php'; $salt = 'salt$'; // get POST information from login form $email = mysqli_escape_string($read, $_POST["email"]); $password = mysqli_escape_string($read, $_POST["password"]); //Hash the password $password = openssl_digest($password . $salt, 'sha512'); //Prepare the sequel query and bind parameters $stmt = $read->prepare('SELECT email, password FROM users WHERE email = ? AND password = ?'); $stmt->bind_param('ss', $email, $password); //Retrieves data from user table if (!$stmt->execute()) { header('Location: /login.php?message=Login%20Failed'); die; } $stmt->store_result(); //Check if the password was correct if ($stmt->num_rows()) { //Set session data $_SESSION['user'] = $email; $_SESSION['id'] = authenticated_session($email); header('Location: /index.php'); } else { // logout
/** * Generates a hash value (message digest) according to given algorithm. * It returns RAW binary string. * * This is a wrapper function that uses one of available internal function * dependent on given PHP configuration. It may use various functions from * ext/openssl, ext/hash, ext/mhash or ext/standard. * * @param string $func digest algorithm * @param string $data data to sign * @return string RAW digital signature * @throws \Exception */ public static function digest($func, $data) { if (!isset(self::$signature_algorithms[$func])) { throw new OpenIdCryptoException(sprintf(OpenIdErrorMessages::InvalidMacFunctionMessage, $func)); } $func = self::$signature_algorithms[$func]; if (function_exists('openssl_digest')) { return openssl_digest($data, $func, true); } else { if (function_exists('hash')) { return hash($func, $data, true); } else { if ($func == 'sha1') { return sha1($data, true); } else { if ($func == 'sha256') { if (function_exists('mhash')) { return mhash(MHASH_SHA256, $data); } } } } } throw new \Exception('Unsupported digest algorithm "' . $func . '".'); }
function test_openssl_digest() { $test = "OpenSSL is also good for hashing things"; VS(md5($test), openssl_digest($test, "md5")); }
/** * Generates a hash value (message digest) according to given algorithm. * It returns RAW binary string. * * This is a wrapper function that uses one of available internal function * dependent on given PHP configuration. It may use various functions from * ext/openssl, ext/hash, ext/mhash or ext/standard. * * @param string $func digest algorithm * @param string $data data to sign * @return string RAW digital signature * @throws Zend\OpenId\Exception */ public static function digest($func, $data) { if (function_exists('openssl_digest')) { return openssl_digest($data, $func, true); } else { if (function_exists('hash')) { return hash($func, $data, true); } else { if ($func === 'sha1') { return sha1($data, true); } else { if ($func === 'sha256') { if (function_exists('mhash')) { return mhash(MHASH_SHA256, $data); } } } } } throw new Exception('Unsupported digest algorithm "' . $func . '".', Exception::UNSUPPORTED_DIGEST); }
<?php $data = "openssl_digest() basic test"; $method = "md5"; $method2 = "sha1"; var_dump(openssl_digest($data, $method)); var_dump(openssl_digest($data, $method2));
public function loginCheck($u, $p) { $request = $this->getRequest(); $session = $request->getSession(); $Miusuario = $this->getDoctrine()->getRepository('tutoriasBundle:Persona')->findOneByDni($u); if ($Miusuario != '') { $sal = $Miusuario->getSal(); $hash = openssl_digest($p . $sal, 'sha512'); if ($hash == $Miusuario->getHash() && $Miusuario->getActivo()) { $Miperfil = $Miusuario->getIdperfil(); $unPerfil = $this->getDoctrine()->getRepository('tutoriasBundle:Perfil')->findOneByIdperfil($Miperfil); $session->set('logueado', 'true'); $session->set('idPersona', $Miusuario->getIdpersona()); $session->set('perfil', $Miusuario->getIdperfil()); $session->set('tipo', $unPerfil->getDescripcion()); $session->set('saludo', 'Ingreso'); $session->set('mensaje_session', ''); return true; } else { $session->set('logueado', 'false'); $session->set('idPersona', ''); $session->set('perfil', 0); $session->set('tipo', ''); $session->set('saludo', 'Ingreso'); $session->set('saludo', 'error de login'); return false; } } else { $session->set('logueado', 'false'); $session->set('idPersona', ''); $session->set('perfil', 0); $session->set('tipo', ''); $session->set('saludo', 'Ingreso'); $session->set('saludo', 'error de login'); return false; } }
/** * User constructor. */ public function __construct() { $this->groups = new ArrayCollection(); $seed = new \DateTime(); $this->apiToken = openssl_digest($seed->getTimestamp(), 'sha1'); }
/** * Hashes a password and returns the hash based on the specified enc_type. * * @param string The password to hash in clear text. * @param string Standard LDAP encryption type which must be one of * crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, sha512, or clear. * @return string The hashed password. */ function pla_password_hash($password_clear, $enc_type) { if (DEBUG_ENABLED && (($fargs = func_get_args()) || ($fargs = 'NOARGS'))) { debug_log('Entered (%%)', 1, 0, __FILE__, __LINE__, __METHOD__, $fargs); } $enc_type = strtolower($enc_type); switch ($enc_type) { case 'blowfish': if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH == 0) { error(_('Your system crypt library does not support blowfish encryption.'), 'error', 'index.php'); } # Hardcoded to second blowfish version and set number of rounds $new_value = sprintf('{CRYPT}%s', crypt($password_clear, '$2a$12$' . random_salt(13))); break; case 'crypt': if ($_SESSION[APPCONFIG]->getValue('password', 'no_random_crypt_salt')) { $new_value = sprintf('{CRYPT}%s', crypt($password_clear, substr($password_clear, 0, 2))); } else { $new_value = sprintf('{CRYPT}%s', crypt($password_clear, random_salt(2))); } break; case 'ext_des': # Extended des crypt. see OpenBSD crypt man page. if (!defined('CRYPT_EXT_DES') || CRYPT_EXT_DES == 0) { error(_('Your system crypt library does not support extended DES encryption.'), 'error', 'index.php'); } $new_value = sprintf('{CRYPT}%s', crypt($password_clear, '_' . random_salt(8))); break; case 'k5key': $new_value = sprintf('{K5KEY}%s', $password_clear); system_message(array('title' => _('Unable to Encrypt Password'), 'body' => 'phpLDAPadmin cannot encrypt K5KEY passwords', 'type' => 'warn')); break; case 'md5': $new_value = sprintf('{MD5}%s', base64_encode(pack('H*', md5($password_clear)))); break; case 'md5crypt': if (!defined('CRYPT_MD5') || CRYPT_MD5 == 0) { error(_('Your system crypt library does not support md5crypt encryption.'), 'error', 'index.php'); } $new_value = sprintf('{CRYPT}%s', crypt($password_clear, '$1$' . random_salt(9))); break; case 'sha': # Use php 4.3.0+ sha1 function, if it is available. if (function_exists('sha1')) { $new_value = sprintf('{SHA}%s', base64_encode(pack('H*', sha1($password_clear)))); } elseif (function_exists('mhash')) { $new_value = sprintf('{SHA}%s', base64_encode(mhash(MHASH_SHA1, $password_clear))); } else { error(_('Your PHP install does not have the mhash() function. Cannot do SHA hashes.'), 'error', 'index.php'); } break; case 'ssha': if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) { mt_srand((double) microtime() * 1000000); $salt = mhash_keygen_s2k(MHASH_SHA1, $password_clear, substr(pack('h*', md5(mt_rand())), 0, 8), 4); $new_value = sprintf('{SSHA}%s', base64_encode(mhash(MHASH_SHA1, $password_clear . $salt) . $salt)); } else { error(_('Your PHP install does not have the mhash() or mhash_keygen_s2k() function. Cannot do S2K hashes.'), 'error', 'index.php'); } break; case 'smd5': if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) { mt_srand((double) microtime() * 1000000); $salt = mhash_keygen_s2k(MHASH_MD5, $password_clear, substr(pack('h*', md5(mt_rand())), 0, 8), 4); $new_value = sprintf('{SMD5}%s', base64_encode(mhash(MHASH_MD5, $password_clear . $salt) . $salt)); } else { error(_('Your PHP install does not have the mhash() or mhash_keygen_s2k() function. Cannot do S2K hashes.'), 'error', 'index.php'); } break; case 'sha512': if (function_exists('openssl_digest') && function_exists('base64_encode')) { $new_value = sprintf('{SHA512}%s', base64_encode(openssl_digest($password_clear, 'sha512', true))); } else { error(_('Your PHP install doest not have the openssl_digest() or base64_encode() function. Cannot do SHA512 hashes. '), 'error', 'index.php'); } break; case 'clear': default: $new_value = $password_clear; } return $new_value; }
function __verifyFingerprint($peerFingerprint, $cert) { if (\is_string($peerFingerprint)) { $peerFingerprint = [$peerFingerprint]; } elseif (!\is_array($peerFingerprint)) { throw new CryptoException("Invalid peer_fingerprint; string or array required"); } if (!\openssl_x509_export($cert, $str, false)) { throw new CryptoException("Failed exporting peer cert for fingerprint verification"); } if (!\preg_match("/-+BEGIN CERTIFICATE-+(.+)-+END CERTIFICATE-+/s", $str, $matches)) { throw new CryptoException("Failed parsing cert PEM for fingerprint verification"); } $pem = $matches[1]; $pem = \base64_decode($pem); foreach ($peerFingerprint as $expectedFingerprint) { $algo = \strlen($expectedFingerprint) === 40 ? 'sha1' : 'md5'; $actualFingerprint = \openssl_digest($pem, $algo); if ($expectedFingerprint === $actualFingerprint) { return; } } throw new CryptoException("Peer fingerprint(s) did not match"); }
$_SESSION["notifications"]["message"] = "your email does not have an account yet"; header("location: login-form.php"); } else { $checkPwQuery = "SELECT hashed_password, salt from users where email = :email"; $checkPwQueryStatement = $db->prepare($checkPwQuery); $checkPwQueryStatement->bindParam(":email", $email); $checkPwQueryStatement->execute(); $passwordSaltAr = array(); while ($row = $checkPwQueryStatement->fetch(PDO::FETCH_ASSOC)) { $passwordSaltAr[] = $row; } $passwordToCheck = openssl_digest($password . $passwordSaltAr[0]["salt"], 'sha512'); $originalPassword = $passwordSaltAr[0]["hashed_password"]; if ($passwordToCheck == $originalPassword) { unset($_SESSION["login"]); $hashedEmailSalt = openssl_digest($email . $passwordSaltAr[0]["salt"], 'sha512'); setcookie("login", $email . "," . $hashedEmailSalt, time() + 2592000); header("location: dashboard.php"); } else { $_SESSION["notifications"]["type"] = "error"; $_SESSION["notifications"]["message"] = "Wrong password"; header("location: login-form.php"); } } } catch (PDOException $e) { $_SESSION["notifications"]["type"] = "database error"; $_SESSION["notifications"]["message"] = $e->getMessage(); header("location: login-form.php"); } } else { $_SESSION["notifications"]["type"] = "error";
public function loginCheck($u, $p) { $Miusuario = $this->getDoctrine()->getRepository('tutoriasBundle:Persona')->findOneByLegajo($u); $Miperfil = $Miusuario->getIdperfil(); $unPerfil = $this->getDoctrine()->getRepository('tutoriasBundle:Perfil')->findOneByIdperfil($Miperfil); $sal = $Miusuario->getSal(); $hash = openssl_digest($p . $sal, 'sha512'); $checkeado = false; if ($hash == $Miusuario->getHash()) { //print_r($p); //print_r($sal); //print_r($hash); //$distro = $Miusuario->getHash(); //echo "<br>"; //print_r($distro ); $_SESSION['logueado'] = 'true'; $_SESSION['idPersona'] = $Miusuario->getIdpersona(); $_SESSION['perfil'] = $Miusuario->getIdperfil(); $_SESSION['tipo'] = $unPerfil->getDescripcion(); $_SESSION['saludo'] = 'Ingreso'; return true; } else { $_SESSION['saludo'] = 'error de login'; return false; } }
public static function digest($data, $func, $rawOutput = false) { $return = openssl_digest($data, $func, $rawOutput); self::handleReturn($return); return $return; }
public function alta_alumno_inAction() { $request = $this->getRequest(); $session = $request->getSession(); $dni = $request->request->get('dni'); $Miusuario = $this->getDoctrine()->getRepository('tutoriasBundle:Persona')->findOneByDni($dni); if ($this->VerificoPerfil('alta_alumno_in')) { $persona = new Persona(); $nombre = $request->request->get('nombre'); $apellido = $request->request->get('apellido'); $legajo = $request->request->get('legajo'); $dni = $request->request->get('dni'); $email = $request->request->get('email'); $password = $request->request->get('password'); $salCodifided = openssl_random_pseudo_bytes(32); //$sal = (string)$sal; //$sal =rand(5, 15); $sal = utf8_encode($salCodifided); $hash = openssl_digest($password . $sal, 'sha512'); $domicilio = $request->request->get('domicilio'); $piso = $request->request->get('piso'); // hay un problema con el almacenamiento de la fecha en la base de datos $unDato = $request->request->get('fecha_nac'); $fecha = new \Datetime($unDato); $idprovincia = $request->request->get('idProvincia'); $idciudad = $request->request->get('idCiudad'); $idtiporesidencia = $request->request->get('idTiporesidencia'); $genero = $request->request->get('genero'); $numero = $request->request->get('numero'); $dpto = $request->request->get('departamento'); $localidad = $request->request->get('localidad'); $telefono = $request->request->get('telefono'); $celular = $request->request->get('celular'); $conviviente = $request->request->get('conviviente'); $idtrabajo = $request->request->get('idTrabajo'); $idhorastrabajo = $request->request->get('idHorastrabajo'); $idtitulo = $request->request->get('idTitulo'); $iddeporte = $request->request->get('idDeporte'); $sosteneconomico = $request->request->get('sosteneconomico'); $sostenfamilia = $request->request->get('sostenfamilia'); $edadhijos = $request->request->get('edadhijos'); $idnacionalidad = $request->request->get('idNacionalidad'); $persona->setNombre($nombre); $persona->setApellido($apellido); $persona->setLegajo($legajo); $persona->setEmail($email); $persona->setSal($sal); $persona->setHash($hash); $persona->setIdperfil(4); // 4 - idperfil alumno $persona->setDni($dni); $persona->setActivo(0); $em = $this->getDoctrine()->getManager(); $em->persist($persona); $em->flush(); $Alumno = new Alumno(); $Alumno->setIdpersona($persona->getIdpersona()); $Alumno->setDomicilioLocal($domicilio); $Alumno->setIdprovincia($idprovincia); $Alumno->setIdnacionalidad($idnacionalidad); $Alumno->setNumero($numero); $Alumno->setDni($dni); $Alumno->setFechaNacimiento($fecha); $Alumno->setGenero($genero); $Alumno->setIdciudadOrigen($idciudad); $Alumno->setDepto($dpto); $Alumno->setLocalidad($localidad); $Alumno->setTelefono($telefono); $Alumno->setCelular($celular); $Alumno->setIddeporte($iddeporte); $Alumno->setConviviente($conviviente); $Alumno->setSosteneconomico($sosteneconomico); $Alumno->setSostenfamilia($sostenfamilia); $Alumno->setEdadhijos($edadhijos); $Alumno->setIdtrabajo($idtrabajo); $Alumno->setIdtitulo($idtitulo); $Alumno->setIdtiporesidencia($idtiporesidencia); $em->persist($Alumno); $em->flush(); $mensaje = "Alta exitosa!"; return $this->redirectToRoute('tutorias_alta_alumno', array('usuario' => $session->get('Usuario'), 'mensaje' => $mensaje), 301); } else { return $this->redirectToRoute('tutorias_homepage', array('usuario' => $session->get('Usuario')), 301); } #} #else{ # $mensaje='Error: ya existe una persona con ese DNI'; # return $this->redirectToRoute('tutorias_alta_alumno', array('usuario' => $session->get('Usuario'),'mensaje'=>$mensaje), 301); #} }
/** * @return mixed */ public function getHash($salt) { $ola_hash = openssl_digest($this->__toString() . "|" . $salt, 'sha512'); return $ola_hash; }
} if (!empty($emailArray)) { $_SESSION["notifications"]["type"] = "error"; $_SESSION["notifications"]["message"] = "You email already exists"; header("location: registreer.php"); } else { $randomSalt = uniqid(mt_rand(), true); $passwordConcatination = $password . $randomSalt; $hashed_pass = openssl_digest($passwordConcatination, 'sha512'); $insertQuery = "INSERT into users (email, salt, hashed_password, last_login_time) \n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues(:email, :salt, :hashed_password, NOW())"; $insertStatement = $db->prepare($insertQuery); $insertStatement->bindParam(":email", $email); $insertStatement->bindParam(":salt", $randomSalt); $insertStatement->bindParam(":hashed_password", $hashed_pass); $insertStatement->execute(); $hashedEmailSalt = openssl_digest($email . $randomSalt, 'sha512'); setcookie("login", $email . "," . $hashedEmailSalt, time() + 2592000); unset($_SESSION["registration"]); header("location: dashboard.php"); } } catch (PDOException $e) { $_SESSION["notifications"]["type"] = "databaseError"; $_SESSION["notifications"]["message"] = "Problem with database link, please contact the webmaster"; header("location: registreer.php"); } } } } function generatePassWord($length, $uppercase = false, $lowercase = true, $special = false, $number = false) { $test = "";
$checkSaltQuery = ' SELECT salt FROM users WHERE email = :email '; $checkSaltStatement = $db->prepare($checkSaltQuery); $checkSaltStatement->bindValue(':email', $email); $checkSaltStatement->execute(); $saltArray = array(); while ($row = $checkSaltStatement->fetch(PDO::FETCH_ASSOC)) { $saltArray[] = $row; //get values } $salt = $saltArray[0]['salt']; //get 'salt' value from columns //hash //Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string. $hashedEmailAndSalt = openssl_digest($email . $salt, 'sha512'); //check if hashed email/salt is thesame as the hash from the database, if so: user is realy the same user if ($hashedEmailAndSalt == $hash) { $validation = true; setcookie('validation', $validation, time() + 2592000); //30days } else { //setcookie("cookieName", $value, time()+3600); /* expire in 1 hour */ setcookie('login', null, -1); $_SESSION['message']['type'] = 'ERROR'; $_SESSION['message']['text'] = 'Validation is not correct'; } } else { header('location: login-proces'); $_SESSION['message']['type'] = 'ERROR'; $_SESSION['message']['text'] = 'You first need to login';